mongodb $unwind 用于非理想嵌套文档 [英] mongodb $unwind for non-ideal nested document

查看:21
本文介绍了mongodb $unwind 用于非理想嵌套文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm aware that the below mongodb document may not be in an ideal structure, but is there any way to unwind that $rounds.round_values?

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

I've tried with aggregate([{"$unwind": "$rounds"}]), or "$rounds.round_values" but that doesn't seem to work. Any suggestions are greatly appreciated.

{ 
    "_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 显示必填字段
    • $unwind deconstruct the rounds array
    • $project to show required fields
    • 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 将上面的合并对象替换为根
      • $mergeObjects to merge required fields from root and round_values object
      • $replaceRoot to replace above merged object to root
      db.collection.aggregate([
        { $unwind: "$rounds" },
        {
          $replaceRoot: {
            newRoot: {
              $mergeObjects: [
                {
                  GameID: "$GameID",
                  ComputerName: "$ComputerName"
                },
                "$rounds.round_values"
              ]
            }
          }
        }
      ])
      

      游乐场

      这篇关于mongodb $unwind 用于非理想嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆