Reputation: 15002
I want to find those patients who he/she had got nose allergic then got nose cancer.
So the following data should return the user Jack.
Only Jack meets the query conditions.
Please give me some similar queries are similar to this kind of problem. Thanks so much
{
"id": 1,
"name": "Mary",
"symptoms": "nose allerge",
"datetime": "2011-04-02"
},
{
"id": 2,
"name": "Jack",
"symptoms": "nose allerge",
"datetime": "2011-04-02"
},
{
"id": 3,
"name": "Mark",
"symptoms": "nose allerge",
"datetime": "2010-01-02"
},
....
{
"id": 4,
"name": "Jack",
"symptoms": "nose cancer",
"datetime": "2015-04-09"
},
{
"id": 5,
"name": "Mary",
"symptoms": "nose cancer",
"datetime": "2010-09-02"
},
Upvotes: 0
Views: 89
Reputation: 103365
Try the following aggregation pipeline which first filters documents on the two symptoms in question, then sorts the resulting documents in the next pipeline by datetime
descending which can then be grouped by name and get those ordered symptoms pushed to an array diagnosis
. You then further filter the resulting documents from the previous grouping pipeline by matching on the first diagnosis array element that has value "nose cancer"
because that should be the latest symptom and with then second element being "nose allerge"
. You finally have your patient through $project
operation:
db.collection.aggregate([
{
$match: {
symptoms: { $in: ["nose allerge", "nose cancer"] }
}
},
{
$sort: { datetime: -1 }
},/**/
{
$group: {
_id: "$name",
"diagnosis": {
"$push": "$symptoms"
}
}
},
{
$match: {
"diagnosis.0": "nose cancer",
"diagnosis.1": "nose allerge"
}
},
{
$project: {
name: "$_id",
symptoms: "$diagnosis",
_id: 0
}
}
])
Result:
{
"result" : [
{
"name" : "Jack",
"symptoms" : [
"nose cancer",
"nose allerge"
]
}
],
"ok" : 1.0000000000000000
}
Upvotes: 2