MongoDB索引(ensureIndex)

时间:2012-03-28 18:10:47

标签: mongodb indexing

例如我有这样的文档的集合foo:

{"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}]}

两种索引之间有什么区别:

  1. ensureIndex({ “tag_cloud”})
  2. ensureIndex({ “tag_cloud.value”}); ensureIndex({ “tag_cloud.count”})
  3. 在请求的上下文中:

    db.foo.find({"tag_cloud.value":"games"}).sort({"tag_cloud.count":-1});
    

    谢谢!!!

1 个答案:

答案 0 :(得分:4)

MongoDB每个查询一次只能使用一个索引,因此建议创建两个索引的建议不起作用。相反,我会创建一个复合索引:

> db.foo.ensureIndex({"tag_cloud.value": 1, "tag_cloud.count": -1})

此索引既可以用于过滤到您想要考虑的特定元素,也可以按降序排序返回:

> db.foo.find({"tag_cloud.value":"games"}).sort({"tag_cloud.count":-1}).explain()
{
    "cursor" : "BtreeCursor tag_cloud.value_1_tag_cloud.count_-1",
    "isMultiKey" : true,
    "n" : NumberLong(2),
    "nscannedObjects" : NumberLong(2),
    "nscanned" : NumberLong(2),
    ...