Error the update operation document must contain atomic operators

Bug: Model.updateOne() with options { overwrite: true, upsert: true } throws this error: MongoError: the update operation document must contain atomic operators. Reprodruce: const mongoose = requir...

Bug:

Model.updateOne() with options { overwrite: true, upsert: true } throws this error:
MongoError: the update operation document must contain atomic operators.

Reprodruce:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });
mongoose.set('debug', true);

const Schema = new mongoose.Schema({ a: Number, b: Number, c: Number });
const Model = mongoose.model('test', Schema);

Model.deleteMany({})
  .then(() => Model.insertMany([{ a: 1, b: 1 }]))
  .then(() => Model.updateOne({ a: 1 }, { a: 1, c: 1 }, { upsert: true, overwrite: true, new: true }))
  .catch(console.error)
  .then(() => process.exit());

Leads to the following output:

Mongoose: tests.deleteMany({}, {})
Mongoose: tests.insertMany([ { _id: 5c543af34fb84afbe4f92d81, a: 1, b: 1, __v: 0 } ], {})
Mongoose: tests.updateOne({ a: 1 }, { a: 1, c: 1, __v: 0 }, { upsert: true, overwrite: true, new: true })
{ MongoError: the update operation document must contain atomic operators.
    at Function.create (/tmp/node_modules/mongodb-core/lib/error.js:43:12)
    at toError (/tmp/node_modules/mongodb/lib/utils.js:149:22)
    at checkForAtomicOperators (/tmp/node_modules/mongodb/lib/operations/collection_ops.js:161:12)
    at Collection.updateOne (/tmp/node_modules/mongodb/lib/collection.js:722:15)
    at NativeCollection.(anonymous function) [as updateOne] (/tmp/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:146:28)
    at NodeCollection.updateOne (/tmp/node_modules/mquery/lib/collection/node.js:82:19)
    at model.Query._updateThunk (/tmp/node_modules/mongoose/lib/query.js:3514:23)
    at model.Query.<anonymous> (/tmp/node_modules/mongoose/lib/query.js:3548:23)
    at model.Query._wrappedThunk [as _updateOne] (/tmp/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
    at process.nextTick (/tmp/node_modules/kareem/index.js:369:33)
    at processTicksAndRejections (internal/process/next_tick.js:74:9)
  driver: true,
  name: 'MongoError',
  [Symbol(mongoErrorContextSymbol)]: {} }

Expected behavior

The document with { a: 1, b: 1, __v: 0 } should have been updated to { a: 1, c: 1, __v: 0 }.

Versions

$ node -v
v11.9.0
$ npm view mongoose version
5.4.8
$ mongo
MongoDB shell version v3.6.5
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.5

In my collection, there is only one document.

> db.c20160712.find()
{ "_id" : ObjectId("57ab909791c3b3a393e9e277"), "Dimension_id" : 2, "Attribute" : "good", "Hour" : "20160712_06", "Frequency_count" : 100

I want to run updateOne to replace the document with another one. But why is there Error: the update operation document must contain atomic operators?

> db.c20160712.updateOne( "Attribute" : "good", "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action", upsert: true )
2016-08-10T16:37:57.089-0400 E QUERY [thread1] Error: the update operation document must contain atomic operators :
DBCollection.prototype.updateOne@src/mongo/shell/crud_api.js:493:1
@(shell):1:1

The second and third arguments in the above command comes from an example in The Definitive Guide to MongoDB: A complete guide to dealing with Big Data …
By Eelco Plugge, David Hows, Peter Membrey, Tim Hawkins

My MongoDB is 3.2.

edited Nov 29 ’18 at 17:56

asked Aug 10 ’16 at 20:50

In my collection, there is only one document.

> db.c20160712.find()
{ "_id" : ObjectId("57ab909791c3b3a393e9e277"), "Dimension_id" : 2, "Attribute" : "good", "Hour" : "20160712_06", "Frequency_count" : 100

I want to run updateOne to replace the document with another one. But why is there Error: the update operation document must contain atomic operators?

> db.c20160712.updateOne( "Attribute" : "good", "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action", upsert: true )
2016-08-10T16:37:57.089-0400 E QUERY [thread1] Error: the update operation document must contain atomic operators :
DBCollection.prototype.updateOne@src/mongo/shell/crud_api.js:493:1
@(shell):1:1

The second and third arguments in the above command comes from an example in The Definitive Guide to MongoDB: A complete guide to dealing with Big Data …
By Eelco Plugge, David Hows, Peter Membrey, Tim Hawkins

My MongoDB is 3.2.

edited Nov 29 ’18 at 17:56

asked Aug 10 ’16 at 20:50

33

In my collection, there is only one document.

> db.c20160712.find()
{ "_id" : ObjectId("57ab909791c3b3a393e9e277"), "Dimension_id" : 2, "Attribute" : "good", "Hour" : "20160712_06", "Frequency_count" : 100

I want to run updateOne to replace the document with another one. But why is there Error: the update operation document must contain atomic operators?

> db.c20160712.updateOne( "Attribute" : "good", "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action", upsert: true )
2016-08-10T16:37:57.089-0400 E QUERY [thread1] Error: the update operation document must contain atomic operators :
DBCollection.prototype.updateOne@src/mongo/shell/crud_api.js:493:1
@(shell):1:1

The second and third arguments in the above command comes from an example in The Definitive Guide to MongoDB: A complete guide to dealing with Big Data …
By Eelco Plugge, David Hows, Peter Membrey, Tim Hawkins

My MongoDB is 3.2.

edited Nov 29 ’18 at 17:56

asked Aug 10 ’16 at 20:50

In my collection, there is only one document.

> db.c20160712.find()
{ "_id" : ObjectId("57ab909791c3b3a393e9e277"), "Dimension_id" : 2, "Attribute" : "good", "Hour" : "20160712_06", "Frequency_count" : 100

I want to run updateOne to replace the document with another one. But why is there Error: the update operation document must contain atomic operators?

> db.c20160712.updateOne( "Attribute" : "good", "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action", upsert: true )
2016-08-10T16:37:57.089-0400 E QUERY [thread1] Error: the update operation document must contain atomic operators :
DBCollection.prototype.updateOne@src/mongo/shell/crud_api.js:493:1
@(shell):1:1

The second and third arguments in the above command comes from an example in The Definitive Guide to MongoDB: A complete guide to dealing with Big Data …
By Eelco Plugge, David Hows, Peter Membrey, Tim Hawkins

My MongoDB is 3.2.

edited Nov 29 ’18 at 17:56

asked Aug 10 ’16 at 20:50

edited Nov 29 ’18 at 17:56

asked Aug 10 ’16 at 20:50

edited Nov 29 ’18 at 17:56

edited Nov 29 ’18 at 17:56

edited Nov 29 ’18 at 17:56

asked Aug 10 ’16 at 20:50

asked Aug 10 ’16 at 20:50

asked Aug 10 ’16 at 20:50

Wrong syntax for the second parameter. Please check the docs. It should be:

db.c20160712.updateOne(
"Attribute" : "good" ,
$set: "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action" ,
upsert: true
);

answered Aug 10 ’16 at 21:09

I believe this was changed as a side-effect of introducing the updateOne method in addition to update() and updateMany() as somewhat of a safeguard to prevent user’s from accidentally overriding an entire document.

You can use the replaceOne() method instead, or an update() without specifying multi:true.

answered Aug 10 ’16 at 21:01

You should use this code because I was also facing the same problem and then I used this code:

updateOne(
_id: new ObjectID(req.params.id) ,
$set: title: req.body.bookName, author: req.body.authorName ,
upsert: true
)

and you should also define ObjectID otherwise the problem will occur again….

const ObjectID = require('mongodb').ObjectID;

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

Your Answer

StackExchange.ifUsing(«editor», function ()
StackExchange.using(«externalEditor», function ()
StackExchange.using(«snippets», function ()
StackExchange.snippets.init();
);
);
, «code-snippets»);

StackExchange.ready(function()
var channelOptions =
tags: «».split(» «),
id: «1»
;
initTagRenderer(«».split(» «), «».split(» «), channelOptions);

StackExchange.using(«externalEditor», function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using(«snippets», function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: ‘answer’,
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: «»,
imageUploader:
brandingHtml: «Powered by u003ca class=»icon-imgur-white» href=»https://imgur.com/»u003eu003c/au003e»,
contentPolicyHtml: «User contributions licensed under u003ca href=»https://creativecommons.org/licenses/by-sa/3.0/»u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href=»https://stackoverflow.com/legal/content-policy»u003e(content policy)u003c/au003e»,
allowUrls: true
,
onDemand: true,
discardSelector: «.discard-answer»
,immediatelyShowMarkdownHelp:true
);

);

Sign up or log in

StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave(‘#login-link’);
);

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

StackExchange.ready(
function ()
StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fstackoverflow.com%2fquestions%2f38883285%2ferror-the-update-operation-document-must-contain-atomic-operators-when-running%23new-answer’, ‘question_page’);

);

Post as a guest

Email

Required, but never shown

Wrong syntax for the second parameter. Please check the docs. It should be:

db.c20160712.updateOne(
"Attribute" : "good" ,
$set: "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action" ,
upsert: true
);

answered Aug 10 ’16 at 21:09

Wrong syntax for the second parameter. Please check the docs. It should be:

db.c20160712.updateOne(
"Attribute" : "good" ,
$set: "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action" ,
upsert: true
);

answered Aug 10 ’16 at 21:09

52

Wrong syntax for the second parameter. Please check the docs. It should be:

db.c20160712.updateOne(
"Attribute" : "good" ,
$set: "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action" ,
upsert: true
);

answered Aug 10 ’16 at 21:09

Wrong syntax for the second parameter. Please check the docs. It should be:

db.c20160712.updateOne(
"Attribute" : "good" ,
$set: "Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action" ,
upsert: true
);

answered Aug 10 ’16 at 21:09

answered Aug 10 ’16 at 21:09

answered Aug 10 ’16 at 21:09

answered Aug 10 ’16 at 21:09

I believe this was changed as a side-effect of introducing the updateOne method in addition to update() and updateMany() as somewhat of a safeguard to prevent user’s from accidentally overriding an entire document.

You can use the replaceOne() method instead, or an update() without specifying multi:true.

answered Aug 10 ’16 at 21:01

I believe this was changed as a side-effect of introducing the updateOne method in addition to update() and updateMany() as somewhat of a safeguard to prevent user’s from accidentally overriding an entire document.

You can use the replaceOne() method instead, or an update() without specifying multi:true.

answered Aug 10 ’16 at 21:01

10

I believe this was changed as a side-effect of introducing the updateOne method in addition to update() and updateMany() as somewhat of a safeguard to prevent user’s from accidentally overriding an entire document.

You can use the replaceOne() method instead, or an update() without specifying multi:true.

answered Aug 10 ’16 at 21:01

I believe this was changed as a side-effect of introducing the updateOne method in addition to update() and updateMany() as somewhat of a safeguard to prevent user’s from accidentally overriding an entire document.

You can use the replaceOne() method instead, or an update() without specifying multi:true.

answered Aug 10 ’16 at 21:01

answered Aug 10 ’16 at 21:01

answered Aug 10 ’16 at 21:01

answered Aug 10 ’16 at 21:01

You should use this code because I was also facing the same problem and then I used this code:

updateOne(
_id: new ObjectID(req.params.id) ,
$set: title: req.body.bookName, author: req.body.authorName ,
upsert: true
)

and you should also define ObjectID otherwise the problem will occur again….

const ObjectID = require('mongodb').ObjectID;

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

You should use this code because I was also facing the same problem and then I used this code:

updateOne(
_id: new ObjectID(req.params.id) ,
$set: title: req.body.bookName, author: req.body.authorName ,
upsert: true
)

and you should also define ObjectID otherwise the problem will occur again….

const ObjectID = require('mongodb').ObjectID;

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

2

You should use this code because I was also facing the same problem and then I used this code:

updateOne(
_id: new ObjectID(req.params.id) ,
$set: title: req.body.bookName, author: req.body.authorName ,
upsert: true
)

and you should also define ObjectID otherwise the problem will occur again….

const ObjectID = require('mongodb').ObjectID;

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

You should use this code because I was also facing the same problem and then I used this code:

updateOne(
_id: new ObjectID(req.params.id) ,
$set: title: req.body.bookName, author: req.body.authorName ,
upsert: true
)

and you should also define ObjectID otherwise the problem will occur again….

const ObjectID = require('mongodb').ObjectID;

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

answered Jul 19 ’18 at 9:01

nagender pratap chauhannagender pratap chauhan

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.

Sign up or log in

StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave(‘#login-link’);
);

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

StackExchange.ready(
function ()
StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2fstackoverflow.com%2fquestions%2f38883285%2ferror-the-update-operation-document-must-contain-atomic-operators-when-running%23new-answer’, ‘question_page’);

);

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave(‘#login-link’);
);

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave(‘#login-link’);
);

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Sign up or log in

StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave(‘#login-link’);
);

Sign up using Email and Password

Sign up using Email and Password

Post as a guest

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Email

Required, but never shown

Wrong syntax for the second parameter. Please check the docs. It should be:

db.c20160712.updateOne(    { "Attribute" : "good" },     { $set: {"Type" : "DVD", "Title" : "Matrix, The", "Released" : 1999, "Genre" : "Action" } },    { upsert: true });

I believe this was changed as a side-effect of introducing the updateOne() method in addition to update() and updateMany() as somewhat of a safeguard to prevent user’s from accidentally overriding an entire document.

You can use the replaceOne() method instead, or an update() without specifying multi:true.


You should use this code because I was also facing the same problem and then I used this code:

updateOne(    { _id: new ObjectID(req.params.id) },    { $set: { title: req.body.bookName, author: req.body.authorName } },    { upsert: true })

and you should also define ObjectID otherwise the problem will occur again.

const ObjectID = require('mongodb').ObjectID;

Таким образом, у меня есть эта проблема с Mongodb 4.2.1 с использованием Robo 3T. Я хочу обновить определенные документы, перемещая поле внутри другого, который является объектом.

Использование update(), как это работает отлично.

db.getCollection('myCollections').update(
    {
        randomId: ObjectId("......."),
    },
    [
        { $set: { "myObject.myField": "$myField" } },
        { $unset: [ "myField" ] }
    ])

Но когда я хочу обновить все свои документы, используя updateMany(), вот так.

db.getCollection('myCollections').updateMany(
    {
        randomId: ObjectId("......."),
    },
    [
        { $set: { "myObject.myField": "$myField" } },
        { $unset: [ "myField" ] }
    ])

У меня ошибка

Failed to execute script.

Error: the update operation document must contain atomic operators 
Details:
DBCollection.prototype.updateMany@src/mongo/shell/crud_api.js:625:1
@(shell):1:1

Я не пробовал использовать оболочку, но, полагаю, она скажет мне то же самое.

Редактировать

Пример документа перед

{
  _id: ...,
  randomId: ObjectId(...),
  myField: 0.5
  myObject: {
    value1: 1,
    ...
  }
  ...
}

После

{
  _id: ...,
  randomId: ObjectId(...),
  myObject: {
    value1: 1,
    myField: 0.5,
    ...
  }
  ...
}

3 ответа

Лучший ответ

Виноват. Я только что попробовал с оболочкой Монго, и она отлично работает. Следует прекратить использовать Robo 3T для обновления.

Извините за беспокойство и спасибо за ответы


2

A.Fe
20 Ноя 2019 в 17:12

Второй параметр updateOne() и updateMany() должен иметь значение Object, поэтому в основном вы используете неправильный синтаксис, попробуйте вот так:

db.getCollection('myCollections').updateMany({
    randomId: ObjectId("......."),
}, {
    $set: {
        "myObject.myField": "$myField"
    },
    $unset: {
        "myField": 1
    }
})


-1

Matheus Hatje
20 Ноя 2019 в 13:35

Обновите документ, используя $rename оператор обновления ; это просто переименование поля.

db.upd.updateOne(
  { randomId: ObjectId("xyz")},
  { $rename: { myField: "myObject.myField" } }
}


1

prasad_
21 Ноя 2019 в 03:09

Понравилась статья? Поделить с друзьями:
  • Error syntax error at or near using
  • Error syntax error at or near serial
  • Error syntax error at or near second
  • Error syntax error at or near return
  • Error syntax error at or near record