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

jonson
  • 105
  • 2
  • 7

1 Answers1

4

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 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. – jonson May 28 '22 at 15:11
  • Hi done update the answer. Think aggregation query is more suitable for your case. – Yong Shun May 28 '22 at 16:10
  • 1
    Hi, Yong Shun, thank you for your idea. It is really helping me to understand mondobd aggregation. – jonson May 30 '22 at 21:24