$lookup foreignField is ObjectId

Hello, I have an extremely hard question, according to docs

Imagine we have collectionOne:

        "_id" : ObjectId("584aac38686860d502929b8b"),
        "brand" : "BMW"
        "vehicule_id" : "584aac38686860d502920000"

And collectionTwo

        "_id" : ObjectId("584aac38686860d502920000"),
        "brand" : "BMW"
        "type" : "cabrio"        

We try to “aggregate” and “$lookup”, as we need to know “type” from collectionTwo, while are requesting data from collectionOne.

Aggregate function:

      from: 'collectionTwo',
      localField: 'vehicule_id',
      foreignField: : '_id', // not working here, as type "String" != "ObjectId", we can search by any field but not "_id"
      as: 'something'

Will be appreciated any help with your code, not links


That is why it is better to keep your ObjectId as ObjectId rather than strings. In addition an ObjectId probably takes less space than it’s string representation.

But your you’re in luck, see the following:

The drawbacks is that each and every string must be converted. Most likely no index can be used because of the conversion. You might need an alternate form of $lookup because you might need to use let and may be enclosed the conversion into an $expr.

1 Like

foreignField accepts only type [String] , but searched value is type [ObjectId], so I can not set use $toObjectId as foreignField accepts only type [String]

Anyone, please? Can you share some code

Yes and the string must be a field name. That is why I wrote

In case you did not find how, see https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#std-label-lookup-join-let

Not working at all, tested with info you provided

For the all guys, sharing solution:
in your aggregate:


                '$lookup': {
                  //searching collection name
                  'from': 'products',
                  //setting variable [searchId] where your string converted to ObjectId
                  'let': {"searchId": {$toObjectId: "$vehicule_id"}}, 
                  //search query with our [searchId] value
                    //searching [searchId] value equals your field [_id]
                    {"$match": {"$expr":[ {"_id": "$$searchId"}]}},
                    //projecting only fields you reaaly need, otherwise you will store all - huge data loads
                    {"$project":{"_id": 1}}


                  'as': 'productInfo'



The post $lookup foreignField is ObjectId - #7 by Il_Chi indicates that it does work with the information I provided.

You did the conversion inside the $let but the ingredients are all there in what I provided.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.