首页 > 解决方案 > mongodb $unwind 用于非理想嵌套文档

问题描述

我知道下面的 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", 
}

标签: mongodbaggregation-frameworkpymongo

解决方案


  • $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"
    }
  }
])

操场


更动态的方法,

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

操场


推荐阅读