MongoDB Indexing (securityIndex)

For example, I have an assembly of documents like this:

{"tag_cloud":[{"value":"games", "count":10}, {"value":"girls", "count":500}]}
{"tag_cloud":[{"value":"games", "count":5}, {"value":"stack", "count":100}]}
{"tag_cloud":[{"value":"mongodb", "count":1000}, {"value":"thread", "count":15}]}


what's the difference between the two types of indexes:

  • ensureIndex ({"tag_cloud"})
  • ensureIndex ({"tag_cloud.value"}); ensureIndex ({"tag_cloud.count"})

in the context of the request:{"tag_cloud.value":"games"}).sort({"tag_cloud.count":-1});




source to share

1 answer

MongoDB can only use one index at a time per query, so your suggestion to create two indexes won't work. Instead, I would create a composite index:

>{"tag_cloud.value": 1, "tag_cloud.count": -1})


This index can be used to both filter for a specific item or items you want to view, and then also return in descending order:

    "cursor" : "BtreeCursor tag_cloud.value_1_tag_cloud.count_-1",
    "isMultiKey" : true,
    "n" : NumberLong(2),
    "nscannedObjects" : NumberLong(2),
    "nscanned" : NumberLong(2),




All Articles