mongodb - 在 mongoDB 中实现一个可以改进查询的索引
问题描述
我目前正在努力为我的查询实现索引。这是原始查询:
*db.getCollection('products').aggregate([
{ $unwind: "$categories" },
{ $unwind: "$categories"},
{$group: {"_id": "$_id","title": {$first:"$title"},
"asin":{$first:"$asin"},
"categories": { $push: "$categories" }} },
{ $match: { "categories": { $in: ['T-Shirts']}} },
{ "$project":{ "_id": 0, "asin":1, "title":1 } } ])*
这是我当前的索引代码:
*var cursor =
db.products.explain("allPlansExecution").find(categories:{"T-Shirts"},{ categories:1, title:1, asin:1, _id:0,})
while (cursor.hasNext()) {
print(cursor.next());
}*
当我运行索引代码时,我应该得到 nReturned 为 8,当前为 0。
有人可以指导我如何做到这一点吗?或者有人可以告诉我他们会添加什么吗?
解决方案
没有一种简单的方法可以索引另一个数组中包含的数组中的各个值。
在这种情况下,由于所讨论的值是字符串,您可以使用文本索引,例如:
db.products.createIndex({"$**":"text"})
然后,您可以使用$text
查询运算符在索引中搜索精确匹配:
db.products.find({$text:{$search:"\"T-Shirts\""}},{_id:0, asin:1, title:1})
推荐阅读
- c# - 使用页面对象模型和页面工厂时如何在 Selenium WebDriver C# 中应用隐式等待
- kubernetes - 关于 kubectl 的查询
- okta - 通过 api 为在 okta 中注册的特定应用启用 MFA
- c# - 将扩展方法中的事件和函数分配为参数
- sql - SQL查询多个选择语句
- javascript - 如何从节点 js 中的另一个文件调用 javascript 类函数?
- c# - 如何在 windowsform 文本框中执行搜索
- salesforce - 一旦机会行项目将使用最大金额产品创建更新机会的帐户
- python-3.x - 我想在列表中找到倒数第二个元素
- sql - 有时使用 nhibernate 的 SaveOrUpdate 会跳过随机值插入数据库