MongoDB查询展开两个数组
展开意味着从输入文档中解构数组字段以输出每个元素的文档。
要展开数组,请在MongoDB聚合中使用$unwind。首先让我们创建一个包含文档的集合-
> db.demo387.insertOne( ... { ... ... "Name" : "101", ... "Details1" : [ ... {Value:100, Value1:50, Value2:40}, ... {Value:200}, ... {Value:300} ... ], ... "Details" : [ ... {Value:100, Value1:30, Value2:26}, ... {Value:200}, ... {Value:300} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5d197022064be7ab44e7f8") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo387.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : [ { "Value" : 100, "Value1" : 50, "Value2" : 40 }, { "Value" : 200 }, { "Value" : 300 } ], "Details" : [ { "Value" : 100, "Value1" : 30, "Value2" : 26 }, { "Value" : 200 }, { "Value" : 300 } ] }
以下是聚合具有多个数组的文档的查询-
> db.demo387.aggregate([ ... { "$unwind": "$Details1" }, ... { "$unwind": "$Details" }, ... { "$match": { "$expr": ... { "$eq": ["$Details1.Value", "$Details.Value"] } ... }} ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 100, "Value1" : 50, "Value2" : 40 }, "Details" : { "Value" : 100, "Value1" : 30, "Value2" : 26 } } { "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 200 }, "Details" : { "Value" : 200 } } { "_id" : ObjectId("5e5d197022064be7ab44e7f8"), "Name" : "101", "Details1" : { "Value" : 300 }, "Details" : { "Value" : 300 } }