0

Using MongoDB with spring mongo, I'm searching for a convenient and efficient way to copy documents matching a specific query and bulk inserting them again to the same collection with one of the attributes changed.

EDIT: Maybe the question wasn't clear enough: I'm not searching for a bulk update: In the collection, I want to find all documents matching foo="bar", change to foo="baz", and insert the changed documents as a copy in the same collection. AFAIR, the mentioned duplicate question doesn't cover this.

Any ideas on this?

Mr.Radar
  • 775
  • 1
  • 11
  • 32

1 Answers1

1

When copy you should make sure that you do not copy the id. Each document has a unique id inside the collection.

You can run the following MongoDB commands:

db.collection.insert({_id: '1234', val: "abcd"})
var existingDocument = db.collection.findOne({_id: '1234'}) // get a local copy of the document.
existingDocument._id = '5678'   // changing the copied document id.

db.collection.insert(existingDocument) // insert into the MongoDB the same document with different id.

Now running the command:

db.collection.find()

Will return

{ "_id" : "1234", "val" : "abcd" }
{ "_id" : "5678", "val" : "abcd" }

In order to update you can use the following command before the insert:

db.collection.update(
   { _id: "5678" },
   { $set: { "val": "xyz" } }
)

Now when running:

db.collection.find()

The result will be:

{ "_id" : "1234", "val" : "abcd" }
{ "_id" : "5678", "val" : "xyz" }
Rotem
  • 1,381
  • 1
  • 11
  • 23