$lookup localField 对数组中特定索引的引用
$lookup localField reference to specific index in array
我有一个排名集合。每个排名都有一个三元组数组(列表)[rank, user_id, score]
。单个文档可能如下所示:
{
"_id" : 33691,
"timestamp" : ISODate("2017-03-03T01:29:31.663Z"),
"ranks" : [
[1, 53982363, 13666235],
[2, 26204263, 5544911],
]
}
现在我想要查看具有完整用户数据的排名,而不仅仅是用户 ID,基本上是与我的 users
集合的连接。我的查询如下所示:
db.getCollection('pokeyen_bet_rankings').aggregate([
{$match: {_id: 33691}},
{$unwind: "$ranks"},
{$lookup: {
from: "users",
localField: "ranks.1",
foreignField: "_id",
as: "user"
}},
{$unwind: "$user"}
])
但不幸的是,它无法将 ranks.1
的 localField
的值识别为 "tuple" 的第二个元素,而是(不存在的)字段 "ranks.1"
显然,因为它与用户不匹配。我的解决方法是像这样首先提取带有投影的第一个元素(在 $unwind
之后):
{$project: {
user_id: {$arrayElemAt: ["$ranks", 1]}
}},
然后将其用作 localField
。但是我想知道是否有更直接的解决方案。
来自docs,
If your localField is an array, you’ll need to add an $unwind
stage to your pipeline.
所以你所做的是正确的推荐方法。
我有一个排名集合。每个排名都有一个三元组数组(列表)[rank, user_id, score]
。单个文档可能如下所示:
{
"_id" : 33691,
"timestamp" : ISODate("2017-03-03T01:29:31.663Z"),
"ranks" : [
[1, 53982363, 13666235],
[2, 26204263, 5544911],
]
}
现在我想要查看具有完整用户数据的排名,而不仅仅是用户 ID,基本上是与我的 users
集合的连接。我的查询如下所示:
db.getCollection('pokeyen_bet_rankings').aggregate([
{$match: {_id: 33691}},
{$unwind: "$ranks"},
{$lookup: {
from: "users",
localField: "ranks.1",
foreignField: "_id",
as: "user"
}},
{$unwind: "$user"}
])
但不幸的是,它无法将 ranks.1
的 localField
的值识别为 "tuple" 的第二个元素,而是(不存在的)字段 "ranks.1"
显然,因为它与用户不匹配。我的解决方法是像这样首先提取带有投影的第一个元素(在 $unwind
之后):
{$project: {
user_id: {$arrayElemAt: ["$ranks", 1]}
}},
然后将其用作 localField
。但是我想知道是否有更直接的解决方案。
来自docs,
If your localField is an array, you’ll need to add an $unwind stage to your pipeline.
所以你所做的是正确的推荐方法。