MongoDB: update every document on one field
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?
In the Mongo shell, or with any Mongodb client:
• For Mongodb >= 3.2:
db.foo.updateMany({}, {$set: {lastLookedAt: Date.now() / 1000}})
See http://docs.mongodb.org/manual/tutorial/modify-documents/#update-multiple-documents
{}
is the condition (the empty condition matches any document) {$set: {lastLookedAt: Date.now() / 1000}}
is what you want to do • For Mongodb >= 2.2:
db.foo.update({}, {$set: {lastLookedAt: Date.now() / 1000}}, { multi: true })
See http://docs.mongodb.org/manual/tutorial/modify-documents/#update-multiple-documents
{}
is the condition (the empty condition matches any document) {$set: {lastLookedAt: Date.now() / 1000}}
is what you want to do {multi: true}
is the "update multiple documents" option • For Mongodb < 2.2:
db.foo.update({}, {$set: {lastLookedAt: Date.now() / 1000}}, false, true)
See https://web.archive.org/web/20120613233453/http://www.mongodb.org/display/DOCS/Updating
{}
is the condition (the empty condition matches any document) {$set: {lastLookedAt: Date.now() / 1000}}
is what you want to do false
is for the "upsert" parameter (insert if not present, or else update - not what you want) true
is for the "multi" parameter (update multiple records) 此代码将对您有所帮助
Model.update({
'type': "newuser"
}, {
$set: {
email: "abc@gmail.com",
phoneNumber:"0123456789"
}
}, {
multi: true
},
function(err, result) {
console.log(result);
console.log(err);
})
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);
链接地址: http://www.djcxy.com/p/88744.html
下一篇: MongoDB:更新一个字段中的每个文档