MongoDB: update every document on one field

后端 未结 4 1407
温柔的废话
温柔的废话 2020-11-27 09:49

I have a collected named foo hypothetically.

Each instance of foo has a field called lastLookedAt which is a UNIX timestamp since epoch. I\

相关标签:
4条回答
  • 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);
            })  
    
    0 讨论(0)
  • 2020-11-27 10:22

    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)
    0 讨论(0)
  • 2020-11-27 10:23

    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

    0 讨论(0)
  • 2020-11-27 10:41

    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);
    
    0 讨论(0)
提交回复
热议问题