为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

幕布斯6054654 2019-10-11 14:35:46
我的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 ] } })有任何想法吗?
查看完整描述

3 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

您现在可以在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

   }}

)


查看完整回答
反对 回复 2019-10-11
  • 3 回答
  • 0 关注
  • 1182 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信