我是MongoDb的新手,希望您对此查询有所帮助。我写了以下聚合管道
db.collection1.aggregate([
{ "$match": { "type" : "L" }},
{ "$facet": {
"ON": [
{ "$match" : {"lampStatus":'ON'}},
{ "$count": "ON" }
],
"OFF": [
{ "$match" : {"lampStatus": 'OFF'}},
{ "$count": "OFF" }
]
} },
{ "$project": {
"ON": { "$ifNull": [{ "$arrayElemAt": ["$ON.ON", 0] }, 0 ] },
"OFF": { "$ifNull": [{ "$arrayElemAt": ["$OFF.OFF", 0] }, 0 ] },
} }
])
并获得此类型的输出
{
"ON" : 0.0,
"OFF": 30
}
但是如何获取json格式的此类输出
/* 1 */
{
"_id": "ON",
"count" : 0.0
}
/* 2 */
{
"_id": "OFF",
"count" : 30.0
}
有人建议我吗?
实际输出
{
"ON" : 0.0,
"OFF" : 30
}
预期输出:
{
"_id" : "ON",
"COUNT" : 0.0
}
/* 2 */
{
"_id" : "OFF",
"COUNT" : 30.0
}
答案 0 :(得分:1)
已更新
db.collection.aggregate([
{ "$match": { "type" : "L" }},
{ "$facet": {
"ON": [
{ "$match" : {"lampStatus":'ON'}},
{ "$count": "ON" }
],
"OFF": [
{ "$match" : {"lampStatus": 'OFF'}},
{ "$count": "OFF" }
]
} },
{"$project": {
myArray: [
{_id:"ON", count: { "$ifNull": [{ "$arrayElemAt": ["$ON.ON", 0] }, 0 ]} },
{_id:"OFF", count: { "$ifNull": [{ "$arrayElemAt": ["$OFF.OFF", 0] }, 0 ] }}
]
}},
{"$unwind":"$myArray"},
{
"$replaceRoot": { newRoot: "$myArray" }
}
])
答案 1 :(得分:1)
如果您需要更多聚合技巧
db.collection1.aggregate([
{ "$match": { "type" : "L" }},
{ "$facet": {
"ON": [{ "$match" : {"lampStatus": "ON" }}, { "$count": "ON" }],
"OFF": [{ "$match" : {"lampStatus": "OFF" }}, { "$count": "OFF" }]
}},
{ "$project": {
"ON": { "$ifNull": [{ "$arrayElemAt": ["$ON.ON", 0] }, 0 ] },
"OFF": { "$ifNull": [{ "$arrayElemAt": ["$OFF.OFF", 0] }, 0 ] },
}},
{ "$project": {
"data": {
"$map": { "input": { "$objectToArray": "$$ROOT" }, "in": { "_id": "$$this.k", "count": "$$this.v" }}
}
}},
{ "$unwind": "$data" },
{ "$replaceRoot": { "newRoot": "$data" }}
])