MongoDB在不同类型但内容相同的字段上执行$ lookup

时间:2019-04-05 13:35:47

标签: mongodb aggregation-framework

我知道在logTable中,"mailID""1234"(字符串)

在mailTable中,"_id"是1234(NumberInt)

但是$lookup可以采取任何措施吗?

日志表

{ 
    "_id" : "mailStuff0234", 
    "mailID" : "1234", 
    "typeState" : "NEW", 
    "changeByType" : "ADMIN" 
}

邮件表

{ 
    "_id" : NumberInt(1234), 
    "user" : "torben@sunnythailand.com", 
    "subject" : "Visit to Atlantis Condo Resort"
}   

这是汇总

db.log.aggregate([ 
    { '$match': { typeState: 'NEW'} },
    { '$lookup': { 
        from: 'mail', 
        localField: 'mailID', 
        foreignField: '_id', 
        as: 'mail' 
    } }, 
    { '$unwind': '$mail' }
], {})

1 个答案:

答案 0 :(得分:1)

MongoDB 4.0引入了$toInt运算符,因此您可以在应用$lookup之前转换mailID的值。

db.log.aggregate([
    {
        $addFields: { mailID: { $toInt: "$mailID" } }
    },
    {
        $lookup: {
            from: "mail",
            localField: "mailID",
            foreignField: "_id",
            as: "mail"
        }
    }
])

您也可以使用$lookup with custom pipeline

db.log.aggregate([
    {
        $lookup: {
            from: "mail",
            let: { mailID: { $toInt: "$mailID" } },
            pipeline: [ { $match: { $expr: { $eq: [ "$_id", "$$mailID" ] } } } ],
            as: "mail"
        }
    }
])