Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the updated document in MongoDB

I need to get the _id (the Mongo ObjectID) of updated document. For this I want to get the updated document. How can I get it?

I tried this:

...
collection.update(oldData, newData, function(err, doc) {
    console.log(docs); // This prints "1" in console. So, it's not a document.
    if (err) { return callback(err); }
    callback(null, doc);
});
...

Can I get it without finding a document by newData/oldData?

like image 312
Ionică Bizău Avatar asked May 02 '13 08:05

Ionică Bizău


People also ask

How can I tell when a document was last updated in MongoDB?

To get last inserted document, use sort() along with limit(1).

What does updateOne return in MongoDB?

In MongoDB, updateOne() method updates a first matched document within the collection based on the given query. When you update your document the value of the _id field remains unchanged. This method updates one document at a time and can also add new fields in the given document.

What is update query in MongoDB?

The update() method updates the values in the existing document in the collections of MongoDB. When you update your document the value of the _id field remains unchanged. By default, the db. collection. update() method updates a single document.


1 Answers

Instead of using .update(), I think you want to use .findAndModify().

An update can update multiple documents, and the second argument of its callback is the number of updated documents (in your case, 1).

With findAndModify, you can update exactly one document (read the documentation on exactly how it differs from update), and the updated document will be passed to the callback function.

like image 124
robertklep Avatar answered Sep 23 '22 08:09

robertklep