简体   繁体   中英

How to return only ONE matching subdocument (not array) from subdocument array in MongoDB?

In my collection:

{ "code": xx1
  "valueList": [
                  { "id": "yy1", "name": "name1"},
                  { "id": "yy2", "name": "name2"},
                  { "id": "yy3", "name": "name3"}              
               ]
},
{ "code": xx2
  "valueList": [
                  { "id": "yy4", "name": "name4"},
                  { "id": "yy5", "name": "name5"},
                  { "id": "yy6", "name": "name6"}              
               ]
}

I want to return specific ONE matching subdocument (not an array), like below:

{ "id": "yy3", "name": "name3"}  

I try below code:

findOne({ "code": "xx1",
          "valueList.name": "yy3"
       })
.select({ "valueList.$": 1});

It returns an array instead:

 {
   "valueList": [{ "id": "yy3", "name": "name3" }]
 }

How can I solve this? Thank you

You can use below aggregation:

db.col.aggregate([
    { $match: { "valueList.id": "yy3" } },
    { $unwind: "$valueList" },
    { $match: { "valueList.id": "yy3" } },
    { $replaceRoot: { newRoot: "$valueList" } }
])

First $match will filter out all unnecessary documents, then you can use $unwind to get valueList item per document and then $match again to get only the one with yy3 in the last stage you can use $replaceRoot to promote valueList item to the top level.

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