Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble updating last document from a query

Tags:

mongodb

Hello I'm new to Mongodb, I am currently trying to update the last document in a query result but having trouble doing so.

I know how to get the last document using

 db.collection.find().sort({$natural:-1}).limit(1)

but how do I update this? I tried doing:

 db.collection.update(db.collection.find().sort({$natural:-1}).limit(1))

But that didn't work. And I don't think:

 db.collection.update(query,update,option).sort({$natural:-1}).limit(1))

would do what i want. I checked the official documentation but couldn't find anything on querying only for the last document.

like image 822
kkawabat Avatar asked Apr 25 '15 19:04

kkawabat


1 Answers

You can use findAndModify to perform an update that requires sorting to identify the document to update:

db.test.findAndModify({
    query: {},
    sort: {$natural: -1},
    update: {$set: {foo: 'bar'}}
})
like image 113
JohnnyHK Avatar answered Nov 15 '22 08:11

JohnnyHK