If i have two collections where one of that have dbref, how is possibile to join using $lookup and dbref?
Asked
Active
Viewed 1,271 times
3
-
1Basically, No. `$lookup` relies on "matching a field" in the other collection. So if one field is of BSON type `DBref` and the other is of `ObjectId` then the two "types" are not the same, and therefore will not match. As a related issue `$lookup` cannot use data in the `DBRef` such as the "collection", and you need to specify manually. So instead of `DBRef` you "should" use a regular `ObjectId` value. One more reason why `DBRef` is "evil". Don't use it. – Neil Lunn Apr 06 '16 at 07:47
-
Possible duplicate of [Mongo how to $lookup with DBRef](https://stackoverflow.com/questions/40622714/mongo-how-to-lookup-with-dbref) – Olivier Maurel Apr 10 '18 at 13:58
1 Answers
0
DBref is a BSON Object and you cannot make a lookup using its value.
BUT, there is a way to do it, transforming a DBRef object into an array. I have written an answer a few months ago describing how to do it.
Short explanation
Say you have DBRef object like this :
myField: DBRef("otherCollection", ObjectId("582abcd85d2dfa67f44127e0")),
Use $objectToArray on myField like this
db.myColl.aggregate([
{
$project: {
transformedDBRef: {$objectToArray: "$myField"},
}
},
])
The result would be an array of two objects, one object for the reference, one for the ObjectId contained within the DBRef, each with a field "k" and a field "v". It will look like this:
transformedDBRef: [{"k" : "$ref","v" : "otherCollection"},{"k" : "$id","v" : ObjectId("582abcd85d2dfa67f44127e0")}
You can then grep the ObjectId. For the complete solution, please check the link above.

Community
- 1
- 1

Olivier Maurel
- 476
- 4
- 16