问题描述
假设我有一个名为 foo
的集合.
I have a collected named foo
hypothetically.
foo
的每个实例都有一个名为 lastLookedAt 的字段,它是自纪元以来的 UNIX 时间戳.我希望能够通过 MongoDB 客户端并将所有现有文档(大约 20,000 个)的时间戳设置为当前时间戳.
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?
推荐答案
无论版本如何,对于您的示例, 是:
Regardless of the version, for your example, the <update>
is:
{ $set: { lastLookedAt: Date.now() / 1000 } }
但是,根据您的 MongoDB 版本,查询看起来会有所不同.无论版本如何,关键在于空条件{}
将匹配任何文档.在 Mongo shell 中,或使用任何 MongoDB 客户端:
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:
db.foo.updateMany( {}, <update> )
{}
是条件(空条件匹配任何文档){}
is the condition (the empty condition matches any document)
db.foo.update( {}, <update>, { multi: true } )
{}
是条件(空条件匹配任何文档){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 )
{}
是条件(空条件匹配任何文档)false
用于 "upsert" 参数true
用于multi"参数(更新多条记录){}
is the condition (the empty condition matches any document)false
is for the "upsert" parametertrue
is for the "multi" parameter (update multiple records)
这篇关于MongoDB:更新一个字段上的每个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!