JayKrish
JayKrish

Reputation: 947

Mongo DB update query performance

I would like to understand which of the below queries would be faster, while doing updates, in mongo db? I want to update few thousands of records at one stretch.

  1. Accumulating the object ids of those records and firing them using $in or using bulk update?

  2. Using one or two fields in the collection which are common for those few thousand records - akin to "where" in sql and firing an update using those fields. These fields might or might not be indexed.

I know that query will be much smaller in the 2nd case as every single "_id" (oid) is not accumulated. Does accumulating _ids and using those to update documents offer any practical performance advantages?

Upvotes: 0

Views: 1197

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

Does accumulating _ids and using those to update documents offer any practical performance advantages?

Yes because MongoDB will certainly use the _id index (idhack).

In the second method - as you observed - you can't tell whether or not an index will be used for a certain field.

So the answer will be: it depends.

If your collection has million of documents or more, and / or the number of search fields is quite large you should prefer the first search method. Especially if the id list size is not small and / or the id values are adjacent.

If your collection is pretty small and you can tolerate a full scan you may prefer the second approach.

In any case, you should testify both methods using explain().

Upvotes: 1

Related Questions