Reputation: 2486
How would I have multiple $or operations? So far I've tried the following but it silently ignores the 2nd $or.
{
$or: [{a: 2}, {a: 3}],
$or: [{b: 5}, {b: 4}]
}
I assume this is because I'm using two identical keys. Is there any way around this?
Upvotes: 92
Views: 36697
Reputation: 2598
Javascript Object can not have two properties with the same name (You have two $or
in your case), and this will happen also with every query that does not respect this rule (only one property will be taken in consideration).
// try this Javascript code
// (this will throw an error in 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) answer should fix your problem, You can also convert your query into one $or
with all possible values, but it can get messy with more values/variables (Not recommended, but it can get rid of the two properties with same name issue).
// 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}] }
]
}
// If you are searching for a match where the value can
// have one of many possible values you can use $in
{
$or: [
{ a: { $in: [2, 3] } },
{ b: { $in: [4, 5] } },
]
}
Upvotes: 2
Reputation: 1313
For multiple like in sql we use $in and for not we use $nin vc is our collection name here.We are finding those string contains cpu or memo.
db.collection('vc').find({ "name" : { $in: [ /cpu/, /memo/ ] } }
Upvotes: -3
Reputation: 43
$and will not do the job, since the 2nd $or will not validate if the first one fails.
From the Mongo man page:
The $and operator uses short-circuit evaluation. If the first expression (e.g. ) evaluates to false, MongoDB will not evaluate the remaining expressions.
Nested $or however should do the trick:
db.things.find({$or: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] })
Upvotes: -6
Reputation: 5595
Mongo 2.0 added an $and operator, so you can do a query like this:
db.things.find({$and: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] })
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24and
Upvotes: 163