如何使用此条件更新MongoDB中的~2,000条记录 [英] How to update ~20,000 records in MongoDB with this criteria

查看:92
本文介绍了如何使用此条件更新MongoDB中的~2,000条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的MongoDB文档:

I have a MongoDB document that looks like the following:

"sport": "NFL",
"team_id": 5,
"week_num": 6,
"meta": {
   .... more data ....,
   "season_year": 2013
}

我想做的是复制 season_year top level文档的key / val,同时将其嵌入 meta 哈希中。所以它会重复,最终结果如下:

What I'd like to do is copy the season_year key/val to the "top level" document, while leaving it also embedded within the meta hash. So it would be duplicated and the end result would look like:

"sport": "NFL",
"team_id": 5,
"week_num": 6,
"season_year": 2013,
"meta": {
   .... more data ....,
   "season_year": 2013
}

是否有一个简单的方法来更新所有我的收藏中的文件与上述逻辑?我使用 MongoDB shell版本:2.4.3

Is there a trivial way to update all of the documents in my collection with the logic described above? I am using MongoDB shell version: 2.4.3

推荐答案

问题是在更新期间,您无法引用要更新的文档。所以你无法在一个查询中实现你想要的。

The problem is that during the update, you can not refer the document you are updating. So you can not achieve what you want in one query.

您需要遍历所有文档并逐个保存:

You need to iterate through all the documents and save them one by one:

db.yourCollection.find({}).forEach(function(doc) {
  doc.season_year = doc.meta.season_year;
  db.yourCollection.save(doc);
});

这篇关于如何使用此条件更新MongoDB中的~2,000条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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