How do I query referenced objects in MongoDB?(如何在 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
}
我想要的是找到所有 Foo 至少有一个 Bar 其 testprop 设置为 true.我试过这个命令,但它没有返回任何结果:
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 ] } })
有什么想法吗?
推荐答案
您现在可以在 Mongo 3.2 中使用 $lookup
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 中查询引用的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 MongoDB 中查询引用的对象?
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
