I'm new to mongodb and currently I'm facing this problem,
db.medical_records.aggregate([
{
"$group": {
"_id": {
"disease_id": "$disease_id" //a string
}, "count": { "$sum": 1 }
}
},
{
"$addFields": {
"disease_id": { "$toObjectId": "$disease_id" }
// i tried to change it into objectID so i could $lookup it
}
},
{
"$lookup": {
"from": "diseases",
"localField": "disease_id",
"foreignField": "_id",
"as": "disease"
}
}
])
this is an example of my medical record collection
{
"_id" : ObjectId("5989c8f13f3958120800682e"),
"disease_id" : "5989c8f13f3958120800682f",
"patient_id" : "5989c8f13f3958120800681f"
}
disease collection
{
"_id" : ObjectId("5989c8f13f3958120800682f"),
"name" : "Culpa autem officia.",
"code" : "Est aperiam."
}
and the result I expect is kind of,
{
"_id" : {disease_id: 5989c8f13f3958120800682f},
"count" : 20,
"disease" : {
"_id" : ObjectId("5989c8f13f3958120800682f"),
"name" : "Culpa autem officia.",
"code" : "Est aperiam."
}
}
I need to join my medical record collection to disease collection as queried above.
When I tried to lookup it to disease collection it failed as foreignField is not the same type as the localField. I've been trying for some time to find a workaround on this problem. And the query above returned another error,
Unrecognized expression '$toObjectId'
This problem might have been asked several times, but I really need a workaround on this problem, please help
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…