首先让我们创建一个包含文档的集合-
> db.demo118.insertOne( ... { ... "Id" : "101", ... "Name" : "Chris", ... "Subjects" : [ ... "MySQL", ... "MongoDB", ... "Java" ... ], ... "Details" : [ ... { ... "Name" : "David", ... S:"MongoDB" ... }, ... { ... "Name" : "Bob", ... S:"Python" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f0c0cd8f64a552dae6364") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo118.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2f0c0cd8f64a552dae6364"), "Id" : "101", "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java" ], "Details" : [ { "Name" : "David", "S" : "MongoDB" }, { "Name" : "Bob", "S" : "Python" } ] }
以下是使用$addFields管道的查询-
> db.demo118.aggregate([ ... { ... "$addFields": { ... "Details": { ... "$filter": { ... "input": "$Details", ... "as": "out", ... "cond": { "$in": ["$$out.S", "$Subjects"] } ... } ... } ... } ... } ... ]).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e2f0c0cd8f64a552dae6364"), "Id" : "101", "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java" ], "Details" : [ { "Name" : "David", "S" : "MongoDB" } ] }