Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

mongodb - How to query with multiple conditions and those conditions are dependent

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"
},
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...