为此,请使用aggregate()
。在这里,我们考虑了3个角色-管理员,来宾和用户。让我们创建一个包含文档的集合-
> db.demo532.insertOne({"Name":"Chris","Type":"Admin"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4a9def4dcbee04fbbbf9") } > db.demo532.insertOne({"Name":"David","Type":"Guest"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4aa3ef4dcbee04fbbbfa") } > db.demo532.insertOne({"Name":"Bob","Type":"User"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8b4ab0ef4dcbee04fbbbfb") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo532.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8b4a9def4dcbee04fbbbf9"), "Name" : "Chris", "Type" : "Admin" } { "_id" : ObjectId("5e8b4aa3ef4dcbee04fbbbfa"), "Name" : "David", "Type" : "Guest" } { "_id" : ObjectId("5e8b4ab0ef4dcbee04fbbbfb"), "Name" : "Bob", "Type" : "User" }
以下是获取唯一文档的查询,该文档需要与同一集合中的其他文档进行比较-
> db.demo532.aggregate([ ... {$group: {_id:"$Name", "types":{$addToSet:"$Type"}}}, ... {$project: {_id:1, "types": 1, "isSubset": { $setIsSubset: [ ["Admin"], "$types" ] }}}, ... {$match: {"isSubset": false}}, ... {$group: {_id:"$isSubset", "Name": {$push : "$_id"}}}, ... {$project: {"_id": 0, "Name": 1}}, ... {$unwind: "$Name"} ... ])
这将产生以下输出-
{ "Name" : "David" } { "Name" : "Bob" }