【问题标题】:merge the array elements with another array which is part of mongo collection将数组元素与另一个数组合并,该数组是 mongo 集合的一部分
【发布时间】:2021-06-02 07:24:25
【问题描述】:

我有以下名为 sample_collection 的集合。

{'_id': ObjectId('603e9cc2784fa0d80d8672cd'),
'name': 'balaji',
'**B**': [{'price': 1, 'price_range': 'G'},
 {'price': 6, 'price_range': 'F'},
 {'price': 4, 'price_range': 'C'}]}

我有一个数组,名称为 A = [{'price': 22, 'price_range': 'X'}, {'price': 33, 'price_range': 'U'} ]

我正在尝试将数组 A 的元素合并到名称为 B 的数组中,该数组是上述集合的一部分,带有以下 pymongo 查询。

db.sample_collection.update_one({"name": "balaji"}, {"$addToSet": {"B": A}})

但是,我看到整个数组正在与上述集合合并,如下所示。

[{'_id': ObjectId('603e9cc2784fa0d80d8672cd'),
'name': 'balaji',
'B': [{'price': 1, 'price_range': 'G'},
{'price': 6, 'price_range': 'F'},
{'price': 4, 'price_range': 'C'},
[{'price': 22, 'price_range': "X"}
{'price': 33, 'price_range': 'U'}]]} (we can see another square brackets for 22 and 33)

但是我需要将数组 A 的元素(而不是数组本身)与集合数组 B 合并,并且预期的结果需要是

[{'_id': ObjectId('603e9cc2784fa0d80d8672cd'),
'name': 'balaji',
'B': [{'price': 1, 'price_range': 'G'},
{'price': 6, 'price_range': 'F'},
{'price': 4, 'price_range': 'C'},
{'price': 22, 'price_range': "X"}
{'price': 33, 'price_range': 'U'}} (here there are no square brackets for elements with price 22 and 33)

请问上面的查询是什么。

【问题讨论】:

  • 看看$each
  • @Joe 确定 :)
  • @Joe,谢谢它有效,如果可能,请在答案中添加此评论,它也可能对其他人有所帮助。

标签: mongodb pymongo pymongo-3.x


【解决方案1】:

要 $push 或 $addToSet 数组的单个成员,请使用 $each 运算符进行更新,例如:

db.sample_collection.update_one({"name": "balaji"}, {"$addToSet": {"B": {$each: A}}})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2022-09-26
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多