Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: update every document on one field

Tags:

mongodb

I have a collected named foo hypothetically.

Each instance of foo has a field called lastLookedAt which is a UNIX timestamp since epoch. I'd like to be able to go through the MongoDB client and set that timestamp for all existing documents (about 20,000 of them) to the current timestamp.

What's the best way of handling this?

like image 403
randombits Avatar asked Sep 27 '22 07:09

randombits


People also ask

How do I update a single field in MongoDB?

To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.

How can I update multiple documents in mongoose?

Mongoose | updateMany() Function The updateMany() function is same as update(), except MongoDB will update all documents that match the filter. It is used when the user wants to update all documents according to the condition.

What is multi true in MongoDB?

To update multiple documents in a collection, set the multi option to true. multi is optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.


2 Answers

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: Date.now() / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2:

db.foo.updateMany( {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2:

db.foo.update( {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2:

db.foo.update( {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)
like image 518
Philippe Plantier Avatar answered Oct 19 '22 19:10

Philippe Plantier


This code will be helpful for you

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  
like image 12
Jitendra Avatar answered Oct 19 '22 21:10

Jitendra