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

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

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

有什么想法吗?

最佳答案

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

https://stackoverflow.com/questions/9621928/

相关文章:

c# - Mongodb -- 使用 c# 驱动程序包含或排除某些元素

mongodb - 如何在 MongoDB 中删除或删除集合?

mongodb - Mongo 计算一组文档中每个值的出现次数

mongodb - Spring数据MongoDb : MappingMongoConverter

python - 如何将 MongoDB 查询转换为 JSON?

mongodb - 使用 Mongo 集合中的特殊字符

mongodb - 使用 $toLower 更新 MongoDB 集合

mongodb - 为什么不用mongodb?

mongodb - 使用mongodb在UTC中存储日期时如何处理时区问题?

python - pymongo-如何为字段以及其他查询参数设置不同的值