从 MongoDB 中展开两个数组
要展开,使用 $展开。$展开会解构输入文档中的一个数组字段,为每个元素输出一个文档。
我们使用文档创建集合 -
> db.demo515.insertOne( ... { ... "details1": [ ... "4700100004" ... ], ... "details2": [ ... "Not Given" ... ], ... "Value1": [ ... "56", ... "45", ... "35", ... ], ... "Value2": [ ... "35", ... "45", ... "56", ... ]} ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e889e51987b6e0e9d18f590") }
使用 find() 方法显示集合中的所有文档 -
> db.demo515.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [ "Not Given" ], "Value1" : [ "56", "45", "35" ], "Value2" : [ "35", "45", "56" ] }
以下是展开两个数组的查询 -
> db.demo515.aggregate([ ... { $unwind: { path: "$Value1", includeArrayIndex : "index1" } }, ... { $unwind: { path: "$Value2", includeArrayIndex : "index2" } }, ... { $project: { ... _id : 1, ... details1: 1, ... details2: 1, ... Value1: 1, ... Value2: 1, ... valid: { $eq: ["$index1", "$index2"] } } ... }, ... { $match: { valid: true } } ... ]);
这将生成以下输出 -
{ "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [ "Not Given" ], "Value1" : "56", "Value2" : "35", "valid" : true } { "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [ "Not Given" ], "Value1" : "45", "Value2" : "45", "valid" : true } { "_id" : ObjectId("5e889e51987b6e0e9d18f590"), "details1" : [ "4700100004" ], "details2" : [ "Not Given" ], "Value1" : "35", "Value2" : "56", "valid" : true }
广告