我怎么会有多个$or操作呢?到目前为止,我已经尝试了以下方法,但它会默默地忽略第二个$or。
{ $or: [{a: 2}, {a: 3}], $or: [{b: 5}, {b: 4}]}
{
$or: [{a: 2}, {a: 3}],
$or: [{b: 5}, {b: 4}]
}
字符串我想这是因为我用了两把一模一样的钥匙。有什么办法解决这个问题吗?
f4t66c6m1#
Mongo 2.0添加了一个$and运算符,所以你可以这样做一个查询:
db.things.find({$and: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] })
字符串http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24and
v1l68za42#
JavaScript对象不能有两个同名的属性(你有两个$or),这也会发生在每个不遵守此规则的查询中(只考虑一个属性)。
$or
// try this Javascript code (this will throw an errors some programming languages)const x = { a: 1, a : 2 };console.log("x:", x);// this will output x: {a: 2} // <= the "a: 1" was gone.
// try this Javascript code (this will throw an errors some programming languages)
const x = { a: 1, a : 2 };
console.log("x:", x);
// this will output x: {a: 2} // <= the "a: 1" was gone.
字符串这应该(Nader)应该可以解决你的问题,你也可以把你的查询转换成一个$or,包含所有可能的值,但是它可能会因为更多的值/变量而变得混乱(不推荐,但是它可以摆脱两个同名的属性问题)。
// this will not work (your question) { $or: [{a: 2}, {a: 3}], $or: [{b: 5}, {b: 4}]}// this will work (I recommend using $and in your use-case){ $or: [ {a: 2, b: 4}, {a: 2, b: 5}, {a: 3, b: 4}, {a: 3, b: 5}, ] }// this is a better solution for your problem (Nader).{ $and: [ { $or: [{a: 2}, {a: 3}] }, { $or: [{b: 5}, {b: 4}] }}
// this will not work (your question)
// this will work (I recommend using $and in your use-case)
$or: [
{a: 2, b: 4},
{a: 2, b: 5},
{a: 3, b: 4},
{a: 3, b: 5},
]
// this is a better solution for your problem (Nader).
$and: [
{ $or: [{a: 2}, {a: 3}] },
{ $or: [{b: 5}, {b: 4}] }
型
xkftehaa3#
对于多个,比如在sql中,我们使用$in,对于不多个,我们使用$nin vc,这是我们的集合名。我们发现这些字符串包含cpu或memo。
db.collection('vc').find({ "name" : { $in: [ /cpu/, /memo/ ] } }
字符串
pdsfdshx4#
$and不会完成这项工作,因为如果第一个失败,第二个$or将不会验证。从Mongo手册页:
嵌套的$or应该可以做到这一点:{$or:[{$or:['a':1},'b':2}]},{$or:['a':2},'b':3}]})
4条答案
按热度按时间f4t66c6m1#
Mongo 2.0添加了一个$and运算符,所以你可以这样做一个查询:
字符串
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24and
v1l68za42#
JavaScript对象不能有两个同名的属性(你有两个
$or
),这也会发生在每个不遵守此规则的查询中(只考虑一个属性)。字符串
这应该(Nader)应该可以解决你的问题,你也可以把你的查询转换成一个
$or
,包含所有可能的值,但是它可能会因为更多的值/变量而变得混乱(不推荐,但是它可以摆脱两个同名的属性问题)。型
xkftehaa3#
对于多个,比如在sql中,我们使用$in,对于不多个,我们使用$nin vc,这是我们的集合名。我们发现这些字符串包含cpu或memo。
字符串
pdsfdshx4#
$and不会完成这项工作,因为如果第一个失败,第二个$or将不会验证。
从Mongo手册页:
嵌套的$or应该可以做到这一点:
{$or:[{$or:['a':1},'b':2}]},{$or:['a':2},'b':3}]})