为什么$ con不使用更新和$ in MongoDB 5.0.6
我在产品集合中有一个单个文档:
{
"_id" : ObjectId("629868369f69156e9a0592b4"),
"product_id" : "2",
"stock" : 4.0,
"stock_history" : 1.0,
"availability" : true
}
如果这样做:
db.getCollection("products").updateOne(
{'product_id': '2'},
{
$set: {
stock: 2.0,
availability: true,
stock_history: {
$cond: [
{$ne: ['$stock', 2.0]},
2,
'$stock'
]
}
}
}
)
基本上我希望该股票更新为2,而stock_history to off toal值为4.0。
而不是这样,库存字段会更新,而stock_history字段则变为:(整个文档)
{
"_id" : ObjectId("629868369f69156e9a0592b4"),
"product_id" : "2",
"stock" : 2.0,
"stock_history" : {
"$cond" : [
{
"$ne" : [
"$stock",
2.0
]
},
2.0,
"$stock"
]
},
"availability" : true
}
我注意到,如果我使用.update而不是.updateone,则可以这样做:
db.getCollection("products").update(
{'product_id': '2'},
[{
$set: {
stock: 2.0,
availability: true,
stock_history: {
$cond: [
{$ne: ['$stock', 2.0]},
2,
'$stock'
]
}
}
}]
)
它可以正常工作。
但是我需要更新,因为稍后我将使用仅支持更新来支持的bulkwrite。
正如我可以看到我的查询和更新的查询之间的区别,是更新具有方括号之间的$ set对象,而updateOne不支持给出此消息:
更新操作文档必须包含原子操作员
我想念什么?
I have this single document in products collection:
{
"_id" : ObjectId("629868369f69156e9a0592b4"),
"product_id" : "2",
"stock" : 4.0,
"stock_history" : 1.0,
"availability" : true
}
If I do this:
db.getCollection("products").updateOne(
{'product_id': '2'},
{
$set: {
stock: 2.0,
availability: true,
stock_history: {
$cond: [
{$ne: ['$stock', 2.0]},
2,
'$stock'
]
}
}
}
)
Basically I want that stock field gets updated to 2 and stock_history to old value, that is 4.0.
Instead of this, the stock field gets updated and stock_history field becomes this: (entire document)
{
"_id" : ObjectId("629868369f69156e9a0592b4"),
"product_id" : "2",
"stock" : 2.0,
"stock_history" : {
"$cond" : [
{
"$ne" : [
"$stock",
2.0
]
},
2.0,
"$stock"
]
},
"availability" : true
}
I have noticed that if I use .update instead of .updateOne like so:
db.getCollection("products").update(
{'product_id': '2'},
[{
$set: {
stock: 2.0,
availability: true,
stock_history: {
$cond: [
{$ne: ['$stock', 2.0]},
2,
'$stock'
]
}
}
}]
)
it works correctly.
But I need updateOne, because later I will use bulkWrite that is supporting only updateOne.
As I can see the difference between my queries with updateOne and update, is that update has the $set object between square brackets, which updateOne does not support giving this message:
the update operation document must contain atomic operators
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
啊,我发现了这个问题。
如果{$ set:...}在方括号之间放置{$ set:...},它也可以使用。
唯一的问题是我使用旧的外壳,用于MongoDB 4.0.2,但是我的服务器是5.0.6,仅来自MongoDB4.2 Update和UpdateOne支持聚合管道。
这就是操作文件必须包含原子操作员的原因。
Ah, I found the problem.
It works with updateOne also if {$set:...} is put between square brackets.
The only problem was that I was using an older shell, for mongodb 4.0.2 , but my server is 5.0.6 and only from mongodb4.2 the update and updateOne supports aggregation pipeline.
That was the cause for the operation document must contain atomic operators.