Skip to main content
 首页 » 编程设计

python之将值移出对象

2025年05月04日17telwanggs

我有一个看起来像这样的 mongo 集合。

[{ 
    "name": "foo", 
    "place": "Paris", 
    "other": { 
        "var1": "asdf", 
        "var2": "asdf", 
        "var3": "sdfw", 
        etc.... 
    } 
},{ 
    "name": "Bar", 
    "place": "Paris", 
    "other": { 
        "var1": "asdf", 
        "var2": "asdf", 
        etc.... 
    } 
}] 

我需要让数据显示如下:

  [{ 
        "name": "foo", 
        "place": "Paris", 
        "var1": "asdf", 
        "var2": "asdf", 
        "var3": "sdfw", 
        etc... 
    },{ 
        "name": "Bar", 
        "place": "Paris", 
        "var1": "asdf", 
        "var2": "asdf", 
        etc.... 
    }] 

所以我希望对象 Other 被删除,但保留所有值在里面。 实现这一目标的最佳方法是什么。 我可以使用 Python3 或 mongo 聚合。

请您参考如下方法:

您可以使用下面的aggregation使用 $replaceRoot和 $mergeObjects

db.collection.aggregate([ 
  { "$replaceRoot": { 
    "newRoot": { "$mergeObjects": ["$other", "$$ROOT"] } 
  }}, 
  { "$project": { "other": 0 }} 
])