简体   繁体   中英

Mongodb Indexing suggestions

All,

I have a mangodb collection with below fields.

  1. _ID
  2. Title
  3. Description
  4. Tags , array

I have created 2 index on _id and tags field. I have created index for people to search the content with help of keywords.

I have created the index with tags:-1 to show the latest inserted records to show first. But even after that it is showing in the ascending order of _id.

How to create the index on tags field to show the last inserted to show first at the same time it should allow me to search on tags field faster .

If the _id field is the default ObjectId which reflects the insertion order, and you want to query all the documents with a specific Tags by descending insertion order, you can use the query as below:

find({ Tags : $value }).sort({ _id : -1 })

For this query, you can create a compound index on { Tags : 1, _id : -1 }. All the documents with the same Tags will be sorted in descending insertion order and this index should work well for this query.

Please note that if you are doing range query on Tags, like:

find({ Tags : { $in : [ $value1, $value2 ] }}).sort({ _id : -1 })
find({ Tags : { $gt : $value}}).sort({ _id : -1})

It wouldn't be able to use the index to sort the result documents, and will need to sort the results in memory. You can run the query with .explain(true) to check the query plan. If scanAndOrder is true, it means the query cannot use the order of documents in the index for returning sorted results.

There are also some documents and blogs relate to indexes and that I'd recommend reading:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM