简体   繁体   中英

MongoDB query for nested array of specific object

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.

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM