Anass Elidrissi
Anass Elidrissi

Reputation: 75

$lookup when foreignField is array

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.

Upvotes: 1

Views: 320

Answers (1)

Ashh
Ashh

Reputation: 46491

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"
}}

Upvotes: 2

Related Questions