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

我的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 ] } })

有任何想法吗?


幕布斯6054654
浏览 1192回答 3
3回答

慕的地10843

您现在可以在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   }})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

MongoDB