为此,您可以aggregate()
在MongoDB中使用。让我们创建一个包含文档的集合-
> db.demo149.insertOne({"Status":40}); { "acknowledged" : true, "insertedId" : ObjectId("5e350386fdf09dd6d08539c4") } > db.demo149.insertOne({"Status":40}); { "acknowledged" : true, "insertedId" : ObjectId("5e350388fdf09dd6d08539c5") } > db.demo149.insertOne({"Status":50}); { "acknowledged" : true, "insertedId" : ObjectId("5e35038afdf09dd6d08539c6") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo149.find();
这将产生以下输出-
{ "_id" : ObjectId("5e350386fdf09dd6d08539c4"), "Status" : 40 } { "_id" : ObjectId("5e350388fdf09dd6d08539c5"), "Status" : 40 } { "_id" : ObjectId("5e35038afdf09dd6d08539c6"), "Status" : 50 }
这是对MongoDB组的查询-
> db.demo149.aggregate([ ... { ... "$group": { ... "_id": null, ... "done": { ... "$push": { ... "$cond": [ ... { "$eq": [ "$Status", 40 ] }, ... { "_id": "$_id", "Status": "$Status" }, ... false ... ] ... } ... }, ... "notdone": { ... "$push": { ... "$cond": [ ... { "$eq": [ "$Status", 50 ] }, ... { "_id": "$_id", "Status": "$Status" }, ... false ... ] ... } ... } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "done": { ... "$setDifference": [ "$done", [false] ] ... }, ... "notdone": { ... "$setDifference": [ "$notdone", [false] ] ... } ... } ... } ... ]);
这将产生以下输出-
{ "done" : [ { "_id" : ObjectId("5e350386fdf09dd6d08539c4"), "Status" : 40 }, { "_id" : ObjectId("5e350388fdf09dd6d08539c5"), "Status" : 40 } ], "notdone" : [ { "_id" : ObjectId("5e35038afdf09dd6d08539c6"), "Status" : 50 } ] }