mongodb $unwind 用于非理想的嵌套文档

mongodb $unwind for non-ideal nested document

我知道以下 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", 
}
  • $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 将上面合并的对象替换为 root
db.collection.aggregate([
  { $unwind: "$rounds" },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          {
            GameID: "$GameID",
            ComputerName: "$ComputerName"
          },
          "$rounds.round_values"
        ]
      }
    }
  }
])

Playground