[英]How to Join two collections in MongoDB and NodeJS with $lookup and DbRef?
如果我有两个集合,其中一个有dbref,如何使用$ lookup和dbref加入?
DBref is a BSON Object and you cannot make a lookup using its value. DBref是BSON对象,您无法使用其值进行查找。
BUT, there is a way to do it, transforming a DBRef object into an array. 但是,有一种方法可以做到这一点,将DBRef对象转换为数组。 I have written an answer a few months ago describing how to do it.
几个月前我写了一个答案,描述了如何做到这一点。
Say you have DBRef object like this : 假设你有这样的DBRef对象:
myField: DBRef("otherCollection", ObjectId("582abcd85d2dfa67f44127e0")),
Use $objectToArray on myField like this 在myField上使用$ objectToArray就像这样
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". 结果将是两个对象的数组,一个用于引用的对象,一个用于DBRef中包含的ObjectId,每个对象具有字段“k”和字段“v”。 It will look like this:
它看起来像这样:
transformedDBRef: [{"k" : "$ref","v" : "otherCollection"},{"k" : "$id","v" : ObjectId("582abcd85d2dfa67f44127e0")}
You can then grep the ObjectId. 然后,您可以grep ObjectId。 For the complete solution, please check the link above.
有关完整的解决方案,请查看上面的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.