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.
foreignField accepts only type [String] , but searched value is type [ObjectId], so I can not set use $toObjectId as foreignField accepts only type [String]
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
"pipeline":[
//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'
}
},