最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to update ~20,000 records in MongoDB with this criteria - Stack Overflow

programmeradmin1浏览0评论

I have a MongoDB document that looks like the following:

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

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
}

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

I have a MongoDB document that looks like the following:

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

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
}

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

Share Improve this question asked Nov 6, 2013 at 23:07 randombitsrandombits 48.6k79 gold badges273 silver badges449 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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);
});
发布评论

评论列表(0)

  1. 暂无评论