0

I am a new mongodb user, this why I am asking this question. I have a document, in this document I have 3 objects under one _id.

When I am filtering { "people.age": { $in: [24] } } I am getting full this document. But I want to see only the matching object. Like for age 24, I just want to see object 2, not object 0 and 1.

Is it possible to show only the matching object? If you kindly explain me it will be helpful for me.

enter image description here

1 Answer 1

5

Use $ for projection.

Query 1

db.collection.find({
  "people.age": {
    $in: [
      24
    ]
  }
},
{
  "people.$": 1
})

Sample Mongo Playground (Query 1)

If you just to search people by certain age, you may use the below query as well:

Query 2

db.collection.find({
  "people.age": 24
},
{
  "people.$": 1
})

Sample Mongo Playground (Query 2)

Note: $ will returns only the first element of the array.


You may look for aggregation query as:

  1. $match - Filter the document by age.
  2. $project - Decorate output documents. With $filter operator to filter the document in people array.
db.collection.aggregate([
  {
    $match: {
      "people.age": 24
    }
  },
  {
    $project: {
      "people": {
        $filter: {
          input: "$people",
          cond: {
            $eq: [
              "$$this.age",
              24
            ]
          }
        }
      }
    }
  }
])

Sample Mongo Playground (Aggregation pipeline)


Reference

Project Specific Array Elements in the Returned Array

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Yong Shun, for you suggestion. But If I have 2 same age in 2 different objects, still I am getting only one result.
Hi done update the answer. Think aggregation query is more suitable for your case.
Hi, Yong Shun, thank you for your idea. It is really helping me to understand mondobd aggregation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.