如何在MongoDB中查询引用的对象? [英] How do I query referenced objects in MongoDB?

查看:317
本文介绍了如何在MongoDB中查询引用的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got two collections in my Mongo database, and the Foos contain references to one or more Bars:

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

Bar: {
   testprop: true
}

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

What I want is to find all of the Foos that have at least one Bar that has its testprop set to true. I've tried this command, but it doesn't return any results:

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

有什么想法吗?

推荐答案

您现在可以使用

You can now do it in Mongo 3.2 using $lookup

$lookup接受四个参数

from:在同一数据库中指定要执行连接的集合.无法对from集合进行分片.

from: Specifies the collection in the same database to perform the join with. The from collection cannot be sharded.

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

localField: Specifies the field from the documents input to the $lookup stage. $lookup performs an equality match on the localField to the foreignField from the documents of the from collection.

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

foreignField: Specifies the field from the documents in the from collection.

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

as: Specifies the name of the new array field to add to the input documents. The new array field contains the matching documents from the from collection.

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

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

这篇关于如何在MongoDB中查询引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆