Is it possible to compare string with ObjectId via $lookup

瘦欲@ 提交于 2019-12-10 16:35:26

问题


table1 has a field string "value" and table2 has a field "value" as ObjectId, Is it possible to do a query like this or how to write

table1.aggregate([
    { 
        $lookup: { 
            from: "table2", 
            localField: "value", 
            foreignField: "_id", 
            as: "test" 
        }  
    }
])

回答1:


As far I know to join collections using $lookup operator in MongoDB data type should be same. If type mismatch then $lookup will not work. So to join you should use those field that are same type because it check equality.

The $lookup stage does an equality match between a field from the input documents with a field from the documents of the “joined” collection

  • If localField type object then foreignField should be object

  • If localField type string then foreignField should be string

  • If localField type number then foreignField should be number

$lookup Documentation



来源:https://stackoverflow.com/questions/41393899/is-it-possible-to-compare-string-with-objectid-via-lookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!