当我尝试更新更新插入项目时发生此错误:
Updating the path 'x' would create a conflict at 'x'
字段应出现在
$set
或 $setOnInsert
中。两者都没有。
我在使用 PyMongo 执行 update 查询时遇到了同样的问题。
我试图做:
> db.people.update( {'name':'lmn'}, { $inc : { 'key1' : 2 }, $set: { 'key1' : 5 }})
请注意,这里我尝试从两个
MongoDB Update Operators更新
key1
的值。 您不能在更新中多次引用同一路径。例如,即使下面的结果会产生逻辑结果,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'
如果您在更新项目时在
$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'
db.products.update(
{ _id: 1 },
{
$set: { item: "apple" },
$setOnInsert: { defaultQty: 100 }
},
{ upsert: true }
)
以下是问题的关键解释:
MongoDB 创建一个新文档,其 _id 等于 1 条件,然后 将 $set AND $setOnInsert 操作应用于 这份文件。
如果您希望无论插入还是更新都设置或更新字段值,请在 $set 中使用它。如果您希望仅在插入时设置它,请在 $setOnInsert 中使用它。
这是示例:https://docs.mongodb.com/manual/reference/operator/update/setOnInsert/#example
从 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() 也支持
至少在 Ruby 库中,如果两次使用相同的密钥(一次作为符号,一次作为字符串),则可能会出现此错误:
db.getCollection("user").updateOne(
{_id: ...},
{$set: {'name': "Horse", name: "Horse"}}
)
我最近在使用下面的查询时遇到了同样的问题。
TextContainer.findOneAndUpdate({ blockId: req.params.blockId, 'content._id': req.params.noteId }, { $set: { 'content.note': req.body.note } }, { upsert: true, new: true })
当我将
'content.note'
更改为 'content.$.note'
时,它已被修复。所以我的最终查询是:
TextContainer.findOneAndUpdate({ blockId: req.params.blockId, 'content._id': req.params.noteId }, { $set: { 'content.$.note': req.body.note } }, { upsert: true, new: true })
我观察到这里没有提到针对此错误的直接解决方案。 就我而言,我从架构列表中删除了一个 ID,同时添加了一个新 ID,结果出现此错误。
早期代码:
const findProject = await ProjectSchema.findOneAndUpdate(
{ projectId },
{
$addToSet: { projectPolicyList: policyId },
$pull: {projectPolicyList: oldPolicyId}
}
);
因此,一个简单的解决方法是一次更新一个列表。就我而言,我首先添加新元素,然后从列表中删除。
正确代码:
const pushProjectPolicyList = await ProjectSchema.findByIdAndUpdate(projectId,
{ $addToSet: { projectPolicyList: policyId } });
const pullProjectPolicyList = await ProjectSchema.findByIdAndUpdate(projectId,
{ $pull: { projectPolicyList: oldPolicyId } });