更新路径“ x”会在“ x”处产生冲突

时间:2018-06-20 12:01:42

标签: mongodb upsert

当我尝试更新upsert项目时发生此错误: Updating the path 'x' would create a conflict at 'x'

6 个答案:

答案 0 :(得分:14)

字段应显示在$set$setOnInsert中。两者都不是。

答案 1 :(得分:3)

使用PyMongo执行更新查询时,我遇到了同样的问题。
我正在尝试做:


> db.people.update( {'name':'lmn'}, { $inc : { 'key1' : 2 }, $set: { 'key1' : 5 }})

请注意,这里我正在尝试从两个 MongoDB Update Operators 更新key1的值。

当您尝试使用同一查询中的多个 MongoDB更新操作符来更新相同键的值时,就会发生这种情况。

您可以在here

上找到更新运算符的列表

答案 2 :(得分:3)

您不能在更新中多次引用相同的路径。例如,即使下面会产生一些合乎逻辑的结果,MongoDB 也不会允许。

db.getCollection("user").updateOne(
  {_id: ...},
  {$set: {'address': {state: 'CA'}, 'address.city' : 'San Diego'}}
)

你会得到以下错误:

Updating the path 'address.city' would create a conflict at 'address'

答案 3 :(得分:2)

如果在更新项目时在$set$unset中传递相同的密钥,则会收到该错误。

例如:

const body = {
   _id: '47b82d36f33ad21b90'
   name: 'John',
   lastName: 'Smith'
}

MyModel.findByIdAndUpdate(body._id, { $set: body, $unset: {name: 1}})

// Updating the path 'name' would create a conflict at 'name'

答案 4 :(得分:2)

db.products.update(
  { _id: 1 },
  {
     $set: { item: "apple" },
     $setOnInsert: { defaultQty: 100 }
  },
  { upsert: true }
)

以下是该问题的关键说明:

MongoDB通过创建一个_id等于1的新文档。 条件,然后将$ set和$ setOnInsert操作应用于 此文档。

如果要设置或更新字段值而不管插入或更新,请在$ set中使用它。如果只希望在插入时设置它,请在$ setOnInsert中使用它。

这里是示例:https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#example

答案 5 :(得分:1)

从MongoDB 4.2开始,您可以在更新中使用聚合管道:

db.your_collection.update({
    _id: 1
}, 
[{
    $set:{
        x_field: {
            $cond: {
                if: {$eq:[{$type:"$_id"} ,  "missing"]},
                then: 'upsert value',   // it's the upsert case
                else: '$x_field'    // it's the update case
            }
        }
    }
}],
{
     upsert: true
})

db.collection.bulkWrite()也支持它