MongoDB - 降序索引奇怪的行为

标签 mongodb mongodb-query

我的 test 数据库中有这个 test 集合。

[test] 2014-02-11 18:01:33.970 >>> db.test.find ();
{ "_id" : ObjectId("52faa8a695fa10cc7d2b7908"), "x" : 1 }
{ "_id" : ObjectId("52faa8ab95fa10cc7d2b7909"), "x" : 5 }
{ "_id" : ObjectId("52faa8ad95fa10cc7d2b790a"), "x" : 15 }
{ "_id" : ObjectId("52faa8b095fa10cc7d2b790b"), "x" : 25 }
{ "_id" : ObjectId("52faa8b795fa10cc7d2b790c"), "x" : [ 5, 25 ] }

如果我使用

在 x 字段上创建升序索引
[test] 2014-02-11 18:01:50.615 >>> db.test.createIndex({x : 1});

然后这个查找查询工作正常并返回预期结果:

[test] 2014-02-11 18:01:48.72 >>> db.test.find ( { x : {$gt: 10, $lt: 20} } ).min({x:10}).max({x:20});
{ "_id" : ObjectId("52faa8ad95fa10cc7d2b790a"), "x" : 15 }
[test] 2014-02-11 18:01:50.615 >>>

Buf 如果删除该升序索引,然后使用

创建降序索引
[test] 2014-02-11 18:01:50.615 >>> db.test.createIndex({x : -1});

然后相同的查找查询返回此错误:

error: {
        "$err" : "no index found for specified keyPattern: {} min: { x: 10.0 } max: { x: 20.0 }",
        "code" : 10367
}

我期望 MongoDB 会在这里返回相同的文档:

{ "_id" : ObjectId("52faa8ad95fa10cc7d2b790a"), "x" : 15 }      

这对我来说听起来不合逻辑。
这是为什么?为什么 MongoDB 无法在 x 上使用降序索引?

create index
drop index
get indexes

最佳答案

这对我有用:

> db.h.insert({x:15})
> db.h.createIndex({x:-1})
> db.h.find().min({x:20}).max({x:10})
{ "_id" : ObjectId("52fb6930253ac3dcf43b27f5"), "x" : 15 }

您的索引可能有问题。

这样做的原因是因为索引是相反的。

想象一下,你颠倒了一个列表,min 和 max 有效地表示的是获取该列表的一个范围,其中 min 为 10,max 为 20。但是,由于列表是颠倒的,因此该范围不再存在。相反,必须反转范围以匹配列表。

关于MongoDB - 降序索引奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21715121/

相关文章:

mongodb - 在 Mongodb 的嵌套 map 对象模式中选择特定字段

java - 存储为字符串的 Android SQL Lite int 值在检索时显示额外字符

ruby-on-rails - 在 Ruby/Rails 中压缩十六进制字符串

java - CompoundIndex spring 不区分大小写

mongoid - MongoDB 查询一个数组以获得精确的元素匹配,但可能是乱序的

javascript - 查找包含不包含特定值的数组的文档

mongodb - 在 Meteor/React 中实现可撤销的 MongoDB 事务

mongodb - 数组中的多个嵌套组

python - Mongodb 默认在插入时使用当前时间戳

mongodb - 将子文档中的所有字段设置为 false,然后在单个查询中将第二个字段设置为 true