简体   繁体   中英

Find Modify and Insert into the Same Collection of MongoDB

Can any one help me with below case in MongoDB:

  1. find documents with a condition from Collection A. (lets say we got 2 documents)
  2. Modify those 2 documents and then insert into Same collection A , with out disturbing original 2 documents.

Aggregation wont support merge into same collection, I got it through simple javascript, but we need in MapReduce.

Below is my Simple Script:

db.col1.find({
    "field1": "value"
}).forEach(function(d1) {
    d1.f2 = NumberInt(d1.f2 / 10);
    db.col1.save(d1)
})

Before saving the modified document d1, change its _id with a new ObjectId(), this will insert new d1 instead of updating the existing one:

db.col1.find({"field1" : "value"}).forEach(function(d1)
{ 
  d1.f2 = NumberInt(d1.f2/10);
  d1._id = ObjectId(); 
  db.col1.save(d1);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM