Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...