为此,将aggregate()与$filter一起使用。让我们创建一个包含文档的集合-
> db.demo137.insertOne( ... { ... Name1:"Chris", ... Name2:"David", ... Detail1:[ ... {_id:"John", Name3:"Chris"}, ... {_id:"Chris", Name3:"Chris"}, ... ], ... Detail2:[{_id:"David", Name3:"Chris"}, ... {_id:"Carol", Name3:"Chris"}, ... {_id:"John", Name3:"Chris"}] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e31b4cefdf09dd6d08539a0") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo137.find();
这将产生以下输出-
{ "_id" : ObjectId("5e31b4cefdf09dd6d08539a0"), "Name1" : "Chris", "Name2" : "David", "Detail1" : [ { "_id" : "John", "Name3" : "Chris" }, { "_id" : "Chris", "Name3" : "Chris" } ], "Detail2" : [ { "_id" : "David", "Name3" : "Chris" }, { "_id" : "Carol", "Name3" : "Chris" }, { "_id" : "John", "Name3" : "Chris" } ] }
以下是查询以比较聚合过滤器中的两个字段-
> db.demo137.aggregate([ ... { ... $project: { ... _id: 0, ... Name1: 1, ... Name2: 2, ... Detail1: { ... $filter: { ... input: "$Detail1", ... as: "out", ... cond: { ... $eq: ["$$out._id", "$Name1" ] ... } ... } ... }, ... Detail2: { ... $filter: { ... input: "$Detail2", ... as: "out", ... cond: { ... $eq: ["$$out._id", "$Name2" ] ... } ... } ... } ... } ... } ... ])
这将产生以下输出-
{ "Name1" : "Chris", "Name2" : "David", "Detail1" : [ { "_id" : "Chris", "Name3" : "Chris" } ], "Detail2" : [ { "_id" : "David", "Name3" : "Chris" } ] }