Mongoose $lookup 在同一集合中不起作用
我有以下数据集,其中有两种类型的对象通过字段 lType
进行区分,可以是 base
或 extra
。 extra 有一个对 base
位置的引用。
[
{
"_id": "622b6f1c7a0aca9aa252756c",
"country": "US",
"county": "Florida",
"city": "Miami",
"lType": "base",
"displayString": "Florida,Miami",
"__v": 0
},
{
"_id": "622b6f1d7a0aca9aa252756e",
"landmark": "Gas station",
"baseLocation": "622b6f1c7a0aca9aa252756c",
"lType": "extra",
"displayString": "Florida,Miami,Gas station",
"__v": 0
},
{
"_id": "622b6f4c5d0fe602a18826a7",
"country": "US",
"county": "Florida",
"city": "Tampa",
"lType": "base",
"displayString": "Florida,Tampa",
"__v": 0
},
{
"_id": "622b6f4c5d0fe602a18826a9",
"landmark": "Downtown",
"baseLocation": "622b6f4c5d0fe602a18826a7",
"lType": "extra",
"displayString": "Florida,Tampa,Downtown",
"__v": 0
}
]
当我尝试进行这样的聚合查找时,
const location = await Location.collection.aggregate([{
$lookup: {
from: 'location',
localField: 'baseLocation',
foreignField: '_id',
as: 'locationData'
}
}]).toArray();
即使我的 baseLocation
字段是一个 ObjectId,我也会在 locationData
中为我的 extra
位置得到一个空数组指向base
位置对象。
I have the following dataset, where I have two types of objects discriminate by the field lType
that can be either base
or extra
. extra has a ref to a base
location.
[
{
"_id": "622b6f1c7a0aca9aa252756c",
"country": "US",
"county": "Florida",
"city": "Miami",
"lType": "base",
"displayString": "Florida,Miami",
"__v": 0
},
{
"_id": "622b6f1d7a0aca9aa252756e",
"landmark": "Gas station",
"baseLocation": "622b6f1c7a0aca9aa252756c",
"lType": "extra",
"displayString": "Florida,Miami,Gas station",
"__v": 0
},
{
"_id": "622b6f4c5d0fe602a18826a7",
"country": "US",
"county": "Florida",
"city": "Tampa",
"lType": "base",
"displayString": "Florida,Tampa",
"__v": 0
},
{
"_id": "622b6f4c5d0fe602a18826a9",
"landmark": "Downtown",
"baseLocation": "622b6f4c5d0fe602a18826a7",
"lType": "extra",
"displayString": "Florida,Tampa,Downtown",
"__v": 0
}
]
When I try to do an aggregation lookup like this
const location = await Location.collection.aggregate([{
$lookup: {
from: 'location',
localField: 'baseLocation',
foreignField: '_id',
as: 'locationData'
}
}]).toArray();
I get an empty array in locationData
for my extra
locations even though my baseLocation
field is an ObjectId pointing to a base
location object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你有一个错字。不应使用
from: 'location'
,而应为from: 'locations'
。尝试像这样更改您的代码:
工作示例
I think you have a typo. Instead of
from: 'location'
, it should befrom: 'locations'
.Try to change your code like this:
Working example
如果您需要更多“深度”链接位置,您可以使用
“$graphLookup”
。[在加油站找到糖果机。]
在 mongoplayground.net 上尝试一下。
In case you need more "depth" linking locations, you could use
"$graphLookup"
.[Finds the Candy Machine at the Gas Station.]
Try it on mongoplayground.net.