0

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)
})
Luka Čelebić
  • 1,083
  • 11
  • 21
JohnWick
  • 1
  • 2
  • Why do you need MapReduce? – chridam Sep 28 '17 at 08:13
  • Possible dupe https://stackoverflow.com/questions/29487351/how-to-convert-string-to-numerical-values-in-mongodb – chridam Sep 28 '17 at 08:13
  • As I mentioned before I don't want to disturb original data, also if it is aggregation then the out put replaces the collection data instead of merge. If it is Java simple script then data transfer will happen between App & DB servers.So I want it in map reduce to execute on DB Server. – JohnWick Sep 28 '17 at 18:10

1 Answers1

0

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);
})
anhlc
  • 13,839
  • 4
  • 33
  • 40
  • Hey thank you for the quick reply, but unfortunately I'm not looking for this approach. I need the same thing to achieve by using Mapreduce. Thank you. – JohnWick Sep 28 '17 at 03:28