【问题标题】:mongodb $unwind for non-ideal nested documentmongodb $unwind 用于非理想嵌套文档
【发布时间】:2021-06-08 14:05:17
【问题描述】:

我知道下面的 mongodb 文档可能不是一个理想的结构,但是有什么方法可以解开 $rounds.round_values 吗?

我尝试过使用aggregate([{"$unwind": "$rounds"}])"$rounds.round_values",但这似乎不起作用。非常感谢任何建议。

{ 
    "_id" : ObjectId("60bea750c26a1c7095387d00"), 
    "rounds" : [
        {
            "round_number" : "0", 
            "round_values" : {
                "max_player_pot" : "0.25", 
                "pot_multiple" : "0.625", 
               
        }, 
        {
            "round_number" : "1", 
            "round_values" : {
                "max_player_pot" : "0.0", 
                "pot_multiple" : "0.0", 
        }
    ], 
    "GameID" : "392124717", 
    "ComputerName" : "awdfadf", 

}

预期输出:

{ 
    "max_player_pot" : "0.25", 
    "pot_multiple" : "0.625", 
    "GameID" : "392124717", 
    "ComputerName" : "awdfadf", 
},
{
    "max_player_pot" : "0.0", 
    "pot_multiple" : "0.0", 
    "GameID" : "392124717", 
    "ComputerName" : "awdfadf", 
}

【问题讨论】:

  • 究竟是什么问题?它运行良好,请参阅playground
  • 我明白了。是的,它可以展开它,但是我怎样才能将整个结构展平以直接在顶层拥有 round_values?
  • 能否请您显示您的预期结果以获得更清晰的图片?
  • 已编辑问题以澄清

标签: mongodb aggregation-framework pymongo


【解决方案1】:
  • $unwind 解构rounds数组
  • $project 显示必填字段
db.collection.aggregate([
  { $unwind: "$rounds" },
  {
    $project: {
      GameID: 1,
      ComputerName: 1,
      max_player_pot: "$rounds.round_values.max_player_pot",
      pot_multiple: "$rounds.round_values.pot_multiple"
    }
  }
])

Playground


更动态的方法,

  • $mergeObjects 合并来自根和round_values 对象的必填字段
  • $replaceRoot 将上述合并对象替换为根
db.collection.aggregate([
  { $unwind: "$rounds" },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            GameID: "$GameID",
            ComputerName: "$ComputerName"
          },
          "$rounds.round_values"
        ]
      }
    }
  }
])

Playground

【讨论】:

  • 好吧,这很好用,但我有大约 300 个条目。有什么办法可以避免全部输入吗?谢谢
  • 我已经用第二种解决方案更新了答案。
猜你喜欢
  • 1970-01-01
  • 2017-08-27
  • 2020-11-26
  • 2020-11-17
  • 2018-03-09
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 2016-07-01
相关资源
最近更新 更多