$lookup when foreignField is array

守給你的承諾、 提交于 2021-02-10 14:40:49

问题


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
  }]
});

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.

I tried the following:

Anime.aggregate([
    {
      $lookup: {
        'from': 'lists',
        localField: '_id',
        foreignField: 'animes.anime',
        'as': 'name'
      },
    },
    {
      $unwind: '$animes'
    },
    {
      $project:{
        status:'$lists.animes.status'
      }
    }
  ]
)

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.


回答1:


You can use below aggregation

{ "$lookup": {
  "from": "lists",
  "let": { "id": "$_id" },
  "pipeline": [
    { "$match": { "$expr": { "$in": ["$$id", "$animes.anime"] }}},
    { "$unwind": "$animes" },
    { "$match": { "$expr": { "$eq": ["$animes.anime", "$$id"] }}}
  ],
  "as": "name"
}}


来源:https://stackoverflow.com/questions/54539509/lookup-when-foreignfield-is-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!