0%
November 2, 2023

Mongoose way to Convert String into Objectid in Aggregation

mongoose

For example, a $lookup usually involves a linkage with another collection through objectId in pipeline argument.

{
    $lookup: {
        let: { hostUserOid: "$hostUserOid" },
        from: UserModel.collection.name,
        pipeline: [
            {
                $match: {
                    $expr: { $eq: ["$_id", { $toObjectId: "$$hostUserOid" }] }
                }
            }
        ],
        as: "hostUser"
    }
},

Different mongo engine may use different key to convert a string to an ObjectId, in mongodb-java-driver it uses $oid instead of $toObjectId. Aggregation can have slight difference.