$lookup 当 foreignField 是数组时 [英] $lookup when foreignField is array
本文介绍了$lookup 当 foreignField 是数组时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个集合,第一个存储每个用户观看的动画、他们的状态等:
I have 2 collections, the first storing the animes watched by each user, their status etc:
const listSchema = mongoose.Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
animes: [{
_id: false,
anime: {
type: Schema.Types.ObjectId,
ref: 'anime',
unique: true
},
status: String,
episodes: Number,
rating: Number
}]
});
第二个存储所有动漫和相关信息.我想显示第二个集合,但添加从登录用户列表中填充的 status
和 episodes
字段.
and the second storing all animes and the relevant information.
I want to show that second collection but adding status
and episodes
fields that are filled from the list of the logged in user.
我尝试了以下方法:
Anime.aggregate([
{
$lookup: {
'from': 'lists',
localField: '_id',
foreignField: 'animes.anime',
'as': 'name'
},
},
{
$unwind: '$animes'
},
{
$project:{
status:'$lists.animes.status'
}
}
]
)
但它返回一个空数组.我也不知道如何通过 userId
过滤查看 _id
在外部集合中的情况.
but it returns an empty array.
I also don't know how to filter by userId
seeing how the _id
is in the foreign collection.
推荐答案
你可以使用下面的聚合
{ "$lookup": {
"from": "lists",
"let": { "id": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$$id", "$animes.anime"] }}},
{ "$unwind": "$animes" },
{ "$match": { "$expr": { "$eq": ["$animes.anime", "$$id"] }}}
],
"as": "name"
}}
这篇关于$lookup 当 foreignField 是数组时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文