不在 $lookup 中进行转换,先在 $project 转换ObjectId
示例数据:
test1.json
{
_id: ObjectId('64e7237bdb6a520024c61edb'),
name: '基本表'
}
test2.json
{
_id: ObjectId('651137d336ef5b0025157e0b'),
tId: '64e7237bdb6a520024c61edb',
name: '关联表'
}
test2 根据字段 tId 关联查询 test1数据
db.getCollection("test2").aggregate(
{ '$match': { "name": "关联表" } },
{
'$project': {
"TID": {$toObjectId: "$tId"}
'noteCode': 1
}
},
{
'$lookup': {
from: 'test1',
localField: 'TID',
foreignField: '_id',
as: 'info'
}
}
)