Search code examples
arraysmongodbsubdocument

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


Solution

  • 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.