0

I have the following two documents in a mongo collection:

{
    _id: "123",
    name: "n1"
}

{
    _id: "234",
    name: "n2"
}

Let's suppose I read those two documents, and make changes, for example, add "!" to the end of the name. I now want to save the two documents back.

For a single document, there's save, for new documents, I can use insert to save an array of documents.

What is the solution for saving updates to those two documents? The update command asks for a query, but I don't need a query, I already have the documents, I just want to save them back...

I can update one by one, but if that was 2 million documents instead of just two this would not work so well.

One thing to add: we are currently using Mongo v2.4, we can move to 2.6 if Bulk operations are the only solution for this (as that was added in 2.6)

TheZuck
  • 3,513
  • 2
  • 29
  • 36

2 Answers2

0

For this you have 2 options (present in 2.6),

  1. Bulk operations like Mongoimport, mongorestore.

  2. Upsert command for each document.

First option goes better with huge no. of documents (which is your case). In Mongoimport you can use --upsert flag to overwrite the existing documents. You can use --upsert --drop flags to drop existing data and set new document.

This options scales well with lot amount of data in terms of IO and system util.

Upsert command works on in-place update principle. You can use it with a filter but drawback is it works in serial fashion and shouldn't be used for huge data size. Performant only with small data.

Nachiket Kate
  • 8,473
  • 2
  • 27
  • 45
0

When you switch off write concerns, a save doesn't block until the database wrote and returns almost immediately. So with WriteConcern.Unacknowledged, storing 2 million documents with save is a lot quicker than you would think. But no write concerns have the drawback that you won't get any errors from the database.

When you don't want to save them one-by-one, bulk operations are the way to go.

Philipp
  • 67,764
  • 9
  • 118
  • 153