258

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?

randombits
  • 47,058
  • 76
  • 251
  • 433
  • Possible duplicate of [MongoDB: How to update multiple documents with a single command?](http://stackoverflow.com/questions/1740023/mongodb-how-to-update-multiple-documents-with-a-single-command) – Ciro Santilli OurBigBook.com Jan 07 '16 at 01:19

4 Answers4

527

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)
Sled
  • 18,541
  • 27
  • 119
  • 168
Philippe Plantier
  • 7,964
  • 3
  • 27
  • 40
  • Date.now() returns a timestamp, too. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/now – Philippe Plantier Jan 27 '12 at 19:10
  • It's still giving me a date that's no where near right for all of these instances of foo. After running that I do a db.foo.findOne() and lastLookedAt is: 1327691719186, which translates to jruby-1.6.5 :011 > Time.at(1327691719186) => Sun Nov 16 02:19:46 -0500 44042 – randombits Jan 27 '12 at 19:16
  • 1
    My bad, POSIX time uses seconds, whereas Javascript time uses milliseconds. Date.now() / 1000 should work, though. You may have to round it. – Philippe Plantier Jan 27 '12 at 19:20
  • psh it's that empty {} that did it for me, thanks Phil – Jona Apr 13 '16 at 13:10
  • is it possible to do an async call as the value to be updated? for example `{ $set: { status: resultFromApiCall() }}` on all docs in the database? – chovy Dec 12 '16 at 23:19
  • I feel like this answer could be better rewritten so that `{$set: {lastLookedAt: Date.now() / 1000}}` is factored out for better readability – Sled Apr 16 '20 at 15:26
12

This code will be helpful for you

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "abc@gmail.com",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  
Jitendra
  • 189
  • 2
  • 7
7

You can use updateMany() methods of mongodb to update multiple document

Simple query is like this

db.collection.updateMany(filter, update, options)

For more doc of uppdateMany read here

As per your requirement the update code will be like this:

User.updateMany({"created": false}, {"$set":{"created": true}});

here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set

Harsh Patel
  • 6,334
  • 10
  • 40
  • 73
5

I have been using MongoDB .NET driver for a little over a month now. If I were to do it using .NET driver, I would use Update method on the collection object. First, I will construct a query that will get me all the documents I am interested in and do an Update on the fields I want to change. Update in Mongo only affects the first document and to update all documents resulting from the query one needs to use 'Multi' update flag. Sample code follows...

var collection = db.GetCollection("Foo");
var query = Query.GTE("No", 1); // need to construct in such a way that it will give all 20K //docs.
var update = Update.Set("timestamp", datetime.UtcNow);
collection.Update(query, update, UpdateFlags.Multi);
user1163459
  • 128
  • 4