我正在尝试查询MongoDB以获取类似的内容:
“让年龄不在[30,40]范围内的人”
我在做:
db.persons.find({'age' : {$nin : [{$lt : 30},{$gt : 40}]}})
这对我不起作用。我知道我可以做一些年龄<30岁的人和年龄> 40岁的人,但我想知道我是否可以使用“不在”操作员...... 感谢
答案 0 :(得分:2)
如何使用OR conjunction这样:
db.persons.find($or: [{'age': {$lt: 30}},{'age': {$gt : 40}}])
答案 1 :(得分:1)
$ in / $ nin是用于查询列表中离散值的运算符,不能用于范围搜索。
在您的示例中,$ nin的查询必须是
db.persons.find({age:{$nin:[30,31,32,33,34,35,36,37,38,39,40]}})
实际上并不实用,而且不会使用索引:
db.persons.ensureIndex({age:1})
db.persons.find({age:{$nin:[30,31,32,33,34,35,36,37,38,39,40]}}).explain()
{
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
},
"server" : "Aspire-5750:27017"
}
Sgoettschkes上面的答案是正确的,并将使用索引:
db.persons.find({$or: [{'age': {$lt: 30}},{'age': {$gt : 40}}]}).explain()
{
"clauses" : [
{
"cursor" : "BtreeCursor age_1",
"isMultiKey" : false,
"n" : 0,
"nscannedObjects" : 0,
"nscanned" : 0,
"nscannedObjectsAllPlans" : 0,
"nscannedAllPlans" : 0,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 12,
"indexBounds" : {
"age" : [
[
-1.7976931348623157e+308,
30
]
]
}
},
{
"cursor" : "BtreeCursor age_1",
"isMultiKey" : false,
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 0,
"indexBounds" : {
"age" : [
[
40,
1.7976931348623157e+308
]
]
}
}
],
"n" : 1,
"nscannedObjects" : 1,
"nscanned" : 1,
"nscannedObjectsAllPlans" : 1,
"nscannedAllPlans" : 1,
"millis" : 12,
"server" : "Aspire-5750:27017"
}
有关有效查询的详细信息,请参阅http://docs.mongodb.org/manual/core/read-operations/