小编典典

如何在MongoDB中查询引用的对象?

node.js

我的Mongo数据库中有两个集合,并且Foo包含对一个或多个Bars的引用:

Foo: { 
  prop1: true,
  prop2: true,
  bars: [
     {
     "$ref": "Bar",
     "$id": ObjectId("blahblahblah")
     }
  ]
}

Bar: {
   testprop: true
}

我想要的是找到所有Foo至少Bar具有一个testprop设置为true的。我已经尝试过此命令,但不会返回任何结果:

db.Foo.find({ "bars.testprop" : { "$in": [ true ] } })

有任何想法吗?


阅读 255

收藏
2020-07-07

共1个答案

小编典典

您现在可以在Mongo 3.2中使用
$lookup

$lookup 有四个论点

from:在同一数据库中指定要执行联接的集合。from集合无法分片。

localField:指定从文档输入到$ lookup阶段的字段。$
lookup在from集合的文档中对localField和foreignField执行相等的匹配。

foreignField:指定from集合中文档中的字段。

as:指定要添加到输入文档中的新数组字段的名称。新数组字段包含from集合中的匹配文档。

db.Foo.aggregate(
  {$unwind: "$bars"},
  {$lookup: {
    from:"bar",
    localField: "bars",
    foreignField: "_id",
    as: "bar"

   }},
   {$match: {
    "bar.testprop": true
   }}
)
2020-07-07