更新路径‘ x’将在‘ x’处产生冲突

当我尝试更新 upsert 条目时会发生这个错误:

Updating the path 'x' would create a conflict at 'x'
32891 次浏览

Field should appear either in $set, or in $setOnInsert. Not in both.

If you pass the same key in $set and in $unset when updating an item, you will get that error.

For example:

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'

I had the same problem while performing an update query using PyMongo.
I was trying to do:


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

Notice that here I'm trying to update the value of key1 from two MongoDB Update Operators.

This basically happens when you try to update the value of a same key with more than one MongoDB Update Operators within the same query.

You can find a list of Update Operators over here

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

Below is the key explanation to the issue:

MongoDB creates a new document with _id equal to 1 from the condition, and then applies the $set AND $setOnInsert operations to this document.

If you want a field value is set or updated regardless of insertion or update, use it in $set. If you want it to be set only on insertion, use it in $setOnInsert.

Here is the example: https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#example

Starting from MongoDB 4.2 you can use aggregate pipelines in update:

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() also supports it

You cannot have the same path referenced more than once in an update. For example, even though the below would result in something logical, MongoDB will not allow it.

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

You would get the following error:

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

I recently had the same issue while using the query below.

TextContainer.findOneAndUpdate({ blockId: req.params.blockId, 'content._id': req.params.noteId }, { $set: { 'content.note': req.body.note } }, { upsert: true, new: true })

When i have changed 'content.note' to 'content.$.note' it has been fixed. So my final query is :

TextContainer.findOneAndUpdate({ blockId: req.params.blockId, 'content._id': req.params.noteId }, { $set: { 'content.$.note': req.body.note } }, { upsert: true, new: true })

With the Ruby library at least, it's possible to get this error if you have the same key twice, once as a symbol and once as a string:

db.getCollection("user").updateOne(
{_id: ...},
{$set: {'name': "Horse", name: "Horse"}}
)