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?
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" }
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With