Mongodb select 在不知道对象键的情况下从对象获取的信息
Mongodb select information to get from an object without knowing object key
我的数据库中有这些文件
{
"_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
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"
}
}
])
我的数据库中有这些文件
{
"_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
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"
}
}
])