Mongodb $lookup Not working with _id

后端 未结 7 2132
猫巷女王i
猫巷女王i 2020-12-31 09:43

wend try with this query, return the lookup is empty

db.getCollection(\'tests\').aggregate([
    {$match: {typet:\'Req\'}},
    {$project: {incharge:1}},
            


        
相关标签:
7条回答
  • 2020-12-31 10:41

    Your lookup Query is correct. But it is trying to compare a string type (incharge) with ObjectId (_id). Convert the string to ObjectId as shown below. It works for me.

    db.getCollection('tests').aggregate([
    {$match: {typet:'Req'}},
    {$project: {
       incharge:{
         $toObjectId:"$incharge"
       }
    },
    {$lookup:{
            from: "users",
            localField: "incharge", //this is the _id user from tests
            foreignField: "_id", //this is the _id from users
            as: "user"
    }}
    
    0 讨论(0)
提交回复
热议问题