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
151 views
in Technique[技术] by (71.8m points)

Increase Performance in this MongoDB Update

Our collection has roughly 40k documents. Each document has a history array that may contain up to 200 documents.

I need to rename a field in the history array because the current one was somehow created with a trailing space in the name. The following code works but it is super slow.

db.getCollection("mycollection").find({}).forEach ((item) => {
item.history.forEach( (hist) => {
    if (hist.data)
        {
    hist.data.correct_field_name = hist.data["field_name_ending_in_a_space "];
    delete hist.data["field_name_ending_in_a_space "];
        }
});
    db.getCollection("mycollection").save(item);
});
question from:https://stackoverflow.com/questions/65927785/increase-performance-in-this-mongodb-update

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

1 Reply

0 votes
by (71.8m points)

You can run aggregation pipeline to do this on server side:

db.testcol.aggregate([
  {
    //only take docs with wrong field name
    $match: {
      "arrField.wrong name": { $exists: true },
    },
  },
  //unwind so you can then group again with correct field name
  { $unwind: "$arrField" },
  //project your field name correctly, alongwith other fields
  {
    $project: {
      _id: "$_id",
      "arrField.correctName": "$arrField.wrong name",
    },
  },
  //group again as array field
  {
    $group: {
      _id: "$_id",
      arrField: { $push: "$arrField" },
    },
  },
  //dump the output of pipeline into your collection, which will override it. Use with caution!
  {
    $out: "testcol",
  },
]);

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

...