让我们创建一个包含文档的集合-
> db.demo568.insertOne({ _id: 101, details: [ {id : 101 }, { id:103 } ] }); { "acknowledged" : true, "insertedId" : 101 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo568.find();
这将产生以下输出-
{ "_id" : 101, "details" : [ { "id" : 101 }, { "id" : 103 } ] } Following is the query to create second collection: > db.demo569.insertOne({ _id: 101, details: "John" }) { "acknowledged" : true, "insertedId" : 101 } > db.demo569.insertOne({ _id: 102, details: "Chris" }) { "acknowledged" : true, "insertedId" : 102 } > db.demo569.insertOne({ _id: 103, details: "David" }) { "acknowledged" : true, "insertedId" : 103 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo569.find();
这将产生以下输出-
{ "_id" : 101, "details" : "John" } { "_id" : 102, "details" : "Chris" } { "_id" : 103, "details" : "David" }
以下是查询以匹配_id在数组中作为子文档一部分的文档-
> db.demo569.find({ '_id': { '$in': db.demo568.distinct('details.id', {'_id': 101}) }})
这将产生以下输出-
{ "_id" : 101, "details" : "John" } { "_id" : 103, "details" : "David" }