问题
Suppose "A001", "A002", "A003" in symptoms_N means "nose allergic"
Suppose "Z001", "Z002" in symptoms_N means "nose cancer"
I want to find those who got nose cancer AND the had got nose allergic before getting cancer.
For example, the following 2 records hit the target I want.
I can inferred Jack got "nose cancer" on 2015-04-02,
and he had got "nose allergic" on 2011-04-02.
I can find the nose allergic records with $or aggregation operator. like db.collection.find({"$or": OR_CONDITIONS})
I have no idea how to finish the compounded conditions query in MongoDB.
{
"name": "Jack",
"symptoms_1": "B00 ",
"symptoms_2": "A001 ",
"symptoms_3": " ",
"datetime": "2011-04-02"
},
....
{
"name": "Jack",
"symptoms_1": "",
"symptoms_2": "",
"symptoms_3": "Z001",
"datetime": "2015-04-02"
},
回答1:
you put the conditions inside an [ {}, {}, {}, {}] array (since an array is valid json).
db.inventory.find( { $or: [ { "symptom_1": "Z001" }, {"symptom_2": "Z002" }] })
in fact, you might be seeking the $in operator that works on a common field
db.collection.find({ "symptom_1": { $in: ["Z001", "Z002", "A001", "A002", "A003"]});
and it seems you want comb thru all symptom fields so use both $or and $in as such
db.collection.find({$or:
[
{"symptom_1": { $in: ["Z001", "Z002", "A001", "A002", "A003"]}},
{"symptom_2": { $in: ["Z001", "Z002", "A001", "A002", "A003"]}} ,
...
]} );
the braces might be mismatched but start off with that.
来源:https://stackoverflow.com/questions/29405745/how-to-query-with-multiple-conditions-and-those-conditions-are-dependent