MongoDB GroupBy 设置状态
为此,你可以使用 MongoDB 中的 aggregate()。我们创建一个带有文档的集合 -
> 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 } ] }
广告