gpt4 book ai didi

MongoDB 索引 (ensureIndex)

转载 作者:可可西里 更新时间:2023-11-01 09:32:18 24 4
gpt4 key购买 nike

例如我收集了这样的文档 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"})

在请求的上下文中:

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

谢谢!!!

最佳答案

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),
...

关于MongoDB 索引 (ensureIndex),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9913302/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com