Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb: Unsupported conversion from array to objectId in $convert with no onError value

Tags:

mongodb

I use mongodb 4.0.5. I'm using lookup to join two collections, the foreign key is a string value located in request_by array and the other one is ObjectId

{
 $addFields: {
            convertedId: {
                $toObjectId: "$request_by.userId"
            }
        }
}

i want to convert the foreign key to ObjectId so i can join them. But it says "Unsupported conversion from array to objectId in $convert with no onError value"

i have a data something like this:

Simulation collection
    {
        "_id": "8f361e8969948e1c435c06d7",
        "request_by": [{
            "userId": "ae83ccfa592f4963a395263c",
            "iat": 1544801930,
            "exp": 1544819930
        }],
        "status": "finish",
        "start": "2018-12-14T15:39:29.588Z",
        "end": "2018-12-14T16:59:29.538Z",
        "duration": 80,
        "passing_grade": 100,
        "created_at": "2018-12-14T15:39:29.588Z",
        "updated_at": "2018-12-14T15:43:12.897Z",
        "__v": 0
    }

How i can join them if i have data like that?

like image 988
Rahmat Siswanto Avatar asked Oct 17 '25 19:10

Rahmat Siswanto


1 Answers

You need $map since request_by is an array, then you can pass that array directly into $lookup (joins single fields or arrays).

{
    $addFields: {
        convertedId: {
            $map: {
                input: "$request_by",
                as: "r",
                in: { $toObjectId: "$$r.userId" }
            }
        }
    }
}
like image 157
mickl Avatar answered Oct 20 '25 19:10

mickl