如何从 MongoDB 中的子文档数组 return 只有一个匹配的子文档(不是数组)?

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

在我的 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"}              
               ]
}

我想要 return 特定的一个匹配子文档(不是数组),如下所示:

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

我试试下面的代码:

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

它 return 是一个数组:

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

我该如何解决这个问题?谢谢

您可以使用以下聚合:

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

第一个 $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 $replaceRootvalueList 项提升到顶层。