Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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]},
'$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",
"$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]},
'$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?
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.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.