简体   繁体   English

Mongoose / MongoDB如何将嵌套文档作为单个数组查询

[英]Mongoose/MongoDB how to query nested documents as a single array

one item in the collection looks as shown below. 集合中的一项看起来如下所示。

{
"_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
"name" : "MongoDB",
"notes" : [
            {
              "title" : "Hello MongoDB",
              "content" : "Hello MongoDB"
            },
            {
              "title" : "ReplicaSet MongoDB",
              "content" : "ReplicaSet MongoDB"
            }
         ]
}

lets say i want to retrieve all the notes of all documents as a single array, how should i wite my query? 可以说我想以单个数组的形式检索所有文档的所有注释,我应该如何查询? give mongoose and or mongoDB example 给出mongoose和或mongoDB示例

You can use aggregation to get the desires result. 您可以使用聚合来获得期望的结果。 Use a $unwind stage to flatten the array values into documents. 使用$unwind阶段将数组值展平为文档。 Then, follow by a $group stage to $push all the notes into a single array. 然后,在$group阶段之后, $push所有音符$push入单个数组中。 Optionally, use a $project stage to output the expected fields. (可选)使用$project阶段输出期望的字段。

db.collection.aggregate([
    {"$unwind":"$notes"}, 
    {"$group":{"_id": null, "notes":{"$push":"$notes"}}}, 
    {"$project":{"_id":0, "notes":1}}
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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