MongoDB:在一个字段上更新每个文档 [英] MongoDB: update every document on one field

查看:79
本文介绍了MongoDB:在一个字段上更新每个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为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?

推荐答案

无论您使用哪个版本,例如,<update>都是:

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:

$ version> = 3.2 :

$version >= 3.2:

db.foo.updateMany( {}, <update> )

  • {}是条件(空条件匹配任何文档)
    • {} is the condition (the empty condition matches any document)
    • 3.2> $ version> = 2.2 :

      3.2 > $version >= 2.2:

      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 :

          $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" parameter
            • true is for the "multi" parameter (update multiple records)
            • 这篇关于MongoDB:在一个字段上更新每个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆