gpt4 book ai didi

mongodb - 带有复合索引的 Mongo $in

转载 作者:可可西里 更新时间:2023-11-01 09:13:22 25 4
gpt4 key购买 nike

如何在具有复合索引的集合上高效地执行 $in 查找?

索引位于下面示例的字段 a 和 b 上。例如:db.foo.createIndex({a: 1, b: 1})

SQL 示例:

SELECT * 
FROM foo
WHERE (a,b)
IN (
("aVal1", "bVal1"),
("aVal2", "bVal2")
);

我知道你可以这样做:

db.foo.find( {
$or: [
{ a: "aVal1", b: "bVal1" },
{ a: "aVal2", b: "bVal2" },
]
} )

是否有使用 $in 运算符执行此操作的更高效的方法?

最佳答案

因为您已经为(a, b) 创建了一个复合索引,所以您的所有子句表达式都由索引支持-> mongo 将使用索引扫描而不是集合扫描。它可能足够快。

引用:$or Clauses and Indexes

When evaluating the clauses in the $or expression, MongoDB either performs a collection scan or, if all the clauses are supported by indexes, MongoDB performs index scans. That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes. Otherwise, MongoDB will perform a collection scan.

现在关于你的问题

Is there a more performant way to do this using the $in operator?

$in 匹配整个字段。如果你想匹配 (a,b) 那么显然 (a,b) 必须成为一个嵌入对象才能用 $in 搜索。

不确定制作嵌入对象是否符合您当前的架构/要求。但如果是这样的话,$in has known for better performance comparing to $or :

When using $or with that are equality checks for the value of the same field, use the $in operator instead of the $or operator.

在这种情况下,如果您嵌入了如下对象:{e: {a: 'x', b: 'y'}} 然后 db.collections.createIndex({e : 1})$in 配对会加快速度

关于mongodb - 带有复合索引的 Mongo $in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51898076/

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