【问题标题】:Mongodb select information to get from an object without knowing object keyMongodb在不知道对象键的情况下选择从对象获取的信息
【发布时间】:2021-04-13 01:14:35
【问题描述】:

我的数据库中有这些文件

{
"_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 的聚合方法,但找不到我想要的对象

【问题讨论】:

  • 您是否只显示a 值或b 也?
  • 我只想要一个对象
  • 请为您的起始 BSON 文档包含有效的 JSON(您上面显示的不是有效的 JSON)。
  • 完成,包含有效的 json

标签: node.js mongodb mongodb-compass


【解决方案1】:

演示 - 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"
    }
  }
])

【讨论】:

    猜你喜欢
    • 2018-11-28
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    相关资源
    最近更新 更多