我的数据库中有这些文档
{
"_id":"606b583b2506eb000988a8fd",
"lastSync":"2021-04-13T00:10:02.984+00:00",
"Month":{
"2020-12":{
"a":10,
"b":21
},
"2021-01":{
"a":112,
"b":34
},
"2021-03":{
"a":35,
"b":56
},
"2021-02":{
"a":767,
"b":56
},
"2021-04":{
"a":78,
"b":98
}
}
}
我如何查询db.collection.agreggate(query(之类的东西并得到一个数组作为答案:
[
"2020-12":{
"a":10},
"2021-01":{
"a":112},...]
我已经尝试过$project的入侵方法,但就是找不到我想要的对象类型
演示-https://mongoplayground.net/p/v5My6yjrIC0
$map
$replaceRoot
$arrayToObject
$objectToArray
db.collection.aggregate([
{
$replaceRoot: {
"newRoot": {
$arrayToObject: { // convert array to object
$map: { // loop over each item in an array and returns an array
"input": { $objectToArray: "$Month"}, // convert to array
"as": "el",
"in": { k: "$$el.k", v: { a: "$$el.v.a" } // shape the data
}
}
}
}
}
}
])
如果你想在Month内查看此演示-https://mongoplayground.net/p/lD0wPTc_W4Y
db.collection.aggregate([
{
$replaceRoot: {
"newRoot": "$Month"
}
}
])