Vineet Bhatia
Vineet Bhatia

Reputation: 2533

Mongodb 4.4.x - findOneAndUpdate() with $set and $push

I am trying to do a findOneAndUpdate() to Find a document and update it in one atomic operation

db.characters.insertOne({ movies: ['Star Trek'], name: 'Jean-Luc Picard' })

db.characters.findOneAndUpdate({ name: 'Jean-Luc Picard' }, [
    { $set: { age: 59 } },
    { $push: { movies: 'Next Gen' } }
])

gives error

uncaught exception: Error: findAndModifyFailed failed: {
    "ok" : 0,
    "errmsg" : "Unrecognized pipeline stage name: '$push'",
    "code" : 40324,
    "codeName" : "Location40324"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCollection.prototype.findAndModify@src/mongo/shell/collection.js:742:15
DBCollection.prototype.findOneAndUpdate@src/mongo/shell/crud_api.js:910:12
@(shell):1:1

Is there a different syntax to push element to an array? I also tried $addToSet which did not work either.

Upvotes: 2

Views: 580

Answers (1)

Emre Alparslan
Emre Alparslan

Reputation: 1042

Try this, probably will work:

db.characters.findOneAndUpdate({ name: 'Jean-Luc Picard' }, 
{ $set: { age: 59 }, $push: { movies: 'Next Gen' } })

Upvotes: 4

Related Questions