让我们创建一个包含文档的集合-
> 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 }