我在我的节点js app中使用MongoDB和mongoose。我有两个系列:
reasonCollection: {
"_id" : ObjectId("58d8d662f89f8b1d0970797d"),
"name" : "Reason name",
"types": [
ObjectId("58d8d7a67c8f3c1e2e172789"), // id of typesCollection object
ObjectId("58d8d7a67c8f3c1e2e17278e")
]
}
typesCollection: {
"_id" : ObjectId("58d8d7a67c8f3c1e2e172785"),
"name" : "Type name",
"reason" : ObjectId("58d8d662f89f8b1d0970797d"), // id of reasonCollection object
"deductedLeave" : false,
"description" : "",
}
我希望得到一个这样的对象,其中包含所有'的原因'作为它的孩子,所有类型的'有匹配的原因'字段作为其父级。
{
"reasonName": "Reason name",
"reasonId": "reasonCollection ObjectId",
"types": {
"name": "typesCollection object name"
"id": "typesCollection ObjectId"
}
}
我认为在这种情况下我会使用MongoDB的聚合,并过滤结果。
db.reasonCollection.aggregate([
{
'$lookup': {
'from': 'types',
'localField': 'name',
'foreignField': 'types',
'as': 'newData'
}
},
{
'$project': {
'_id': 1,
'name': 1,
'types': 1,
'__v': 1,
'newData': {
'$filter': {
'input': '$newData',
'as': 'element',
'cond': {
'$eq': [ '$$element._id', 'ROOT._id' ] // Here, I need to match reasonId with reasonCollection ObjectId
}
}
}
}
}
])