Mongodb $lookup Not working with _id

后端 未结 7 2130
猫巷女王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:23

    Comparing a string with an ObjectId doesn't throw an error, rather sends an empty array in the aggregated output document. So you need to make sure that you have converted the string object id to mongodb's ObjectId:

    db.getCollection('tests').aggregate([
        {$match: {typet:'Req'}},
        {$set: {incharge: {$toObjectId: "$incharge"} }}, // keep the whole document structure, but replace `incharge` into ObjectId
        {$lookup:{
                from: "users",
                localField: "incharge", //this is the _id user from tests
                foreignField: "_id", //this is the _id from users
                as: "user"
        }}
    ])
    

提交回复
热议问题