我是mongodb的新手,目前我正面临着这个问题,
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"
}
}
])
这是我的医疗记录收集的一个例子
{
"_id" : ObjectId("5989c8f13f3958120800682e"),
"disease_id" : "5989c8f13f3958120800682f",
"patient_id" : "5989c8f13f3958120800681f"
}
疾病收集
{
"_id" : ObjectId("5989c8f13f3958120800682f"),
"name" : "Culpa autem officia.",
"code" : "Est aperiam."
}
而我期望的结果是那种,
{
"_id" : {disease_id: 5989c8f13f3958120800682f},
"count" : 20,
"disease" : {
"_id" : ObjectId("5989c8f13f3958120800682f"),
"name" : "Culpa autem officia.",
"code" : "Est aperiam."
}
}
如上所述,我需要将我的医疗记录收集到疾病收集中 .
当我尝试将其查找到疾病集合时,它失败了,因为foreignField与localField的类型不同 . 我一直在努力寻找解决这个问题的方法 . 上面的查询返回了另一个错误,
Unrecognized expression '$toObjectId'
这个问题可能已被问过几次,但我真的需要解决这个问题,请帮助
2 回答
您无法使用当前的数据结构 .
另见:Mongoose $lookup where localField is a string of an ObjectId in foreignField
在这里:Is it possible to compare string with ObjectId via $lookup
但是,为什么不将医疗记录集中的数据更改为:
给定此格式,您可以使用以下查询获得所需内容:
EDIT 根据您的评论如下:
MongoDB中没有
$toObjectId
运算符 . 试试searching the documentation,你提到了'll find nothing! So there simply is no way to achieve your goal without changing your data. I do not know the 1092316 framework you'但是基于它的文档,我认为你的模型可能需要一些调整 . 你现在如何 Build 你的关系模型?4.0的新功能:https://docs.mongodb.com/manual/reference/operator/aggregation/toObjectId/