什麼對應於aggregation framework中的「case」SQL語句,是$ cond操作符(請參閱manual)。 $ cond語句可以嵌套以模擬「when-then」和「else」,但我選擇了另一種方法,因爲它更易於閱讀(並生成,見下文):我將使用$ concat運算符來編寫範圍字符串,然後作爲分組鍵。
因此,對於給定的集合:
db.xx.find()
{ "_id" : ObjectId("514919fb23700b41723f94dc"), "name" : "A", "timespent" : 100 }
{ "_id" : ObjectId("514919fb23700b41723f94dd"), "name" : "B", "timespent" : 200 }
{ "_id" : ObjectId("514919fb23700b41723f94de"), "name" : "C", "timespent" : 300 }
{ "_id" : ObjectId("514919fb23700b41723f94df"), "name" : "D", "timespent" : 400 }
{ "_id" : ObjectId("514919fb23700b41723f94e0"), "name" : "E", "timespent" : 500 }
骨料(硬編碼)看起來是這樣的:
db.xx.aggregate([
{ $project: {
"_id": 0,
"range": {
$concat: [{
$cond: [ { $lte: ["$timespent", 250] }, "range 0-250", "" ]
}, {
$cond: [ { $and: [
{ $gte: ["$timespent", 251] },
{ $lt: ["$timespent", 450] }
] }, "range 251-450", "" ]
}, {
$cond: [ { $and: [
{ $gte: ["$timespent", 451] },
{ $lt: ["$timespent", 650] }
] }, "range 450-650", "" ]
}]
}
}},
{ $group: { _id: "$range", count: { $sum: 1 } } },
{ $sort: { "_id": 1 } },
]);
,其結果是:
{
"result" : [
{
"_id" : "range 0-250",
"count" : 2
},
{
"_id" : "range 251-450",
"count" : 2
},
{
"_id" : "range 450-650",
"count" : 1
}
],
"ok" : 1
}
爲了產生集合命令,您必須將「範圍」投影構建爲JSON對象(或者您可以生成一個字符串和然後使用JSON.parse(字符串))
發電機看起來像這樣:
var ranges = [ 0, 250, 450, 650 ];
var rangeProj = {
"$concat": []
};
for (i = 1; i < ranges.length; i++) {
rangeProj.$concat.push({
$cond: {
if: {
$and: [{
$gte: [ "$timespent", ranges[i-1] ]
}, {
$lt: [ "$timespent", ranges[i] ]
}]
},
then: "range " + ranges[i-1] + "-" + ranges[i],
else: ""
}
})
}
db.xx.aggregate([{
$project: { "_id": 0, "range": rangeProj }
}, {
$group: { _id: "$range", count: { $sum: 1 } }
}, {
$sort: { "_id": 1 }
}]);
將返回與上述相同的結果。
可能是此鏈接將幫助您 http://stackoverflow.com/questions/8945766/mongodb-mysql-sum-case-when-equivalent/21700596#21700596 – 2014-02-11 11:39:46
http://www.codefari.com/2015 /08/case-statement-in-mongodb-query.html 上面的鏈接可能會幫助您 – Singh 2015-08-26 02:07:36