Question

I am writing a method that updates a single document in a very large MongoCollection, and I have an index that I want the MongoCollection.Update() call to use to drastically reduce lookup time,
but I can't seem to find anything like MongoCursor.SetHint(string indexName).

Is using an index on an update operation possible?
If so, how?

Was it helpful?

Solution 2

If you already have indexed your collection, update will be using the CORRECT index right away. There is no point to provide hint (in fact you can't hint with update).

Hint is only for debugging and testing purposes. Mongo is in most cases smart enough to automatically decide which index (if you have many of them) should be used in a particular query and it reviews its strategy from time to time.

So short answer - do nothing. If you have an index and it is useful, it will be automatically used on find, update, delete, findOne.

If you want to see if it is used - take the part of the query which searches for something and run it through find with explain.

Example for hellboy. This is just an example and in real life it can be more complex. So you have a collection with docs like this {a : int, b : timestamp}. You have 2 indexes: one is on a, another is on b. So right now you need to do a query like a > 5 and b is after 2014. For some reason it uses index a, which does not give you the faster time (may be because you have 1000 elements and most of them are bigger than 5 and only 10 are > 2004 ). SO you decided to hint it to use b index. Cool it works much faster now. But your collection changes and right now you are in 2020 year and most of your documents have b bigger than 2014. So right now your index b is not doing so much work. But mongo still uses it, because you told so.

OTHER TIPS

You can create index according to your query section of update command.

For example if you have this collection, named data:

> db.data.find()
{ "_id" : ObjectId("5334908bd7f87918dae92eaf"), "name" : "omid" }
{ "_id" : ObjectId("5334943fd7f87918dae92eb0"), "name" : "ali" }
{ "_id" : ObjectId("53349478d7f87918dae92eb1"), "name" : "reza" }

and if you do this update query:

> db.data.update(query={name:'ali'}, update={name: 'Ali'})

without any defined index, the number of scanned document is 2:

"nscanned" : 2,

But if you define an index, according to your query, here for name field:

db.data.ensureIndex({name:1})

Now if you update it again:

> db.data.update(query={name:'Ali'}, update={name: 'ALI'})

Mongodb use your index for doing update, and number of scanned document is 1:

"nscanned" : 1,

But if you want to hint for update, you can hint it for your query:

# Assume that the index and field of it exists.
> var cursor = db.data.find({name:'ALI'}).hint({family:1})

Then use it in your update query:

> db.data.update(query=cursor, update={name: 'ALI'})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top