MongoDB查询将计算的表达式推入$ group?
要在$group中推送计算表达式,请使用聚合。首先让我们创建一个包含文档的集合-
> db.demo24.insertOne({"Id":100,"Status":true}); { "acknowledged" : true, "insertedId" : ObjectId("5e14c58722d07d3b95082e72") } > db.demo24.insertOne({"Id":100,"Status":true}); { "acknowledged" : true, "insertedId" : ObjectId("5e14c58a22d07d3b95082e73") } > db.demo24.insertOne({"Id":100,"Status":false}); { "acknowledged" : true, "insertedId" : ObjectId("5e14c58f22d07d3b95082e74") } > db.demo24.insertOne({"Id":100,"Status":true}); { "acknowledged" : true, "insertedId" : ObjectId("5e14c59122d07d3b95082e75") } > db.demo24.insertOne({"Id":100,"Status":false}); { "acknowledged" : true, "insertedId" : ObjectId("5e14c59222d07d3b95082e76") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo24.find();
这将产生以下输出-
{ "_id" : ObjectId("5e14c58722d07d3b95082e72"), "Id" : 100, "Status" : true } { "_id" : ObjectId("5e14c58a22d07d3b95082e73"), "Id" : 100, "Status" : true } { "_id" : ObjectId("5e14c58f22d07d3b95082e74"), "Id" : 100, "Status" : false } { "_id" : ObjectId("5e14c59122d07d3b95082e75"), "Id" : 100, "Status" : true } { "_id" : ObjectId("5e14c59222d07d3b95082e76"), "Id" : 100, "Status" : false }
这是查询(使用$push)将计算的表达式推入$group中的查询-
> db.demo24.aggregate({$group: {_id:'$Id', AllValues: {$push: {$cond: [{$eq: ['$Status', true]},'Active','InActive']}}}})
这将产生以下输出-
{ "_id" : 100, "AllValues" : [ "Active", "Active", "InActive", "Active", "InActive" ] }