【发布时间】:2019-01-17 05:50:50
【问题描述】:
我想从引用的文档中获取字段值。 Mongodb 版本是 3.4。
假设我有 2 个集合 foo 和 bar。 Foo 有对 bar 的引用:
{
"_id" : ObjectId("5b6c713ea502dea387860eba"),
"stack" : "overflow",
"bar" : {
"$ref" : "bar",
"$id" : ObjectId("5b6c70e1a502dea387860ea6"),
"$db" : "stackoverflow"
}
}
而对应的bar文件是这样的:
{
"_id" : ObjectId("5b6c70e1a502dea387860ea6"),
"name" : "bar-2"
}
我尝试了以下聚合函数来归档此结果:
{
"_id" : ObjectId("5b6c713ea502dea387860eba"),
"stack" : "overflow",
"barName" : "bar-2"
}
聚合函数:
db.getCollection('foo').aggregate([
{ $match: { _id: ObjectId("5b6c713ea502dea387860eba") }},
{
$lookup: {
from: 'bar',
localField: 'bar',
foreignField: '_id',
as: "bar"
}
},
{
$project: {
_id: 1,
stack: "$stack",
barName: "$bar.name"
}
}
]).pretty()
但我的结果是这样的:
{
"_id" : ObjectId("5b6c713ea502dea387860eba"),
"stack" : "overflow",
"barName" : []
}
我尝试用谷歌搜索它,我查看了 mongodb 文档但无法找到解决方案。
是我遗漏了什么还是这不可能?
谢谢!
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework aggregate-functions