Nidor
Nidor

Reputation: 85

Mongo Aggregation with nested array of Id´s

I'm having a Model which is structured similar to this:

{
  "_id": ObjectId("5c878c5c18a4ff001b981zh5"),
  "books": [
    ObjectId("5d963a7544ec1b122ab2ddc"),
    ObjectId("5d963be01f663d168f8ea4dc"),
    ObjectId("5d963bcb1f663d168f8ea2f4"),
    ObjectId("5d963bdf1f663d16858ea7c9"),
}

Now I want to use the aggregation framework to get a list of only the populated books, like:

{ _id: ObjectId("5d963a7544ec1b122ab2ddc"), title: ...., ... },
 ..

Upvotes: 0

Views: 712

Answers (2)

Nidor
Nidor

Reputation: 85

So this query worked for me:

{
          $match: {
            _id: user._id,
          },
        },
        {
          $lookup: {
            from: "books",
            localField: "books",
            foreignField: "_id",
            as: "booksInfo",
          },
        },
        { $unwind: "$booksInfo" },
        {
          $replaceRoot: {
            newRoot: "$booksInfo",
          },
        },

Thanks @zishone. Somehow your query returned all the books available in the db and not only the ones from the User Model, but it works as desired when looking up the documents with local and foreignField.

Upvotes: 0

zishone
zishone

Reputation: 1244

.aggregate([
  {
    $lookup: {
      from: 'books',
      let: { books: '$books' },
      pipeline: [{ $match: { $expr: { _id: { $in: ['_id', '$$books'] } } } }],
      as: 'bookInfos'
    }
  },
  { $unwind: '$bookInfos' },
  { $replaceRoot: { newRoot: '$bookInfos' } }
])

I am not too sure about your question, but I think this might be what you're looking for.

Upvotes: 1

Related Questions