S
S
Sergey Filnor2020-10-09 11:12:43
MongoDB
Sergey Filnor, 2020-10-09 11:12:43

How to do two-level aggregation in a query?

Good afternoon!
There are currently 3 collections, with this format:

let item = {
    _id: "...",
}

let itemGroup = {
    _id: "..."
}

let relation = {
    item_id: "...",
    group_id: "..."
}


Previously, this relationship was one-to-one and the item had a group_id, through which we got all the fields using an aggregation of this type:
group.aggregate([
        {
          $project: {
            _id: {
              $toString: '$_id',
            },
            title: 1,
            order: 1,
          },
        },
        {
          $lookup: {
            from: 'fields',
            localField: '_id',
            foreignField: 'group_id',
            as: 'fields',
          },
        },
      ]);


I can't figure out how to make a two-level aggregation with one request - first get all the links, and through it all the elements. Now I divided it into two requests, but the understanding that this can be done by one directly does not let me sleep)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2020-10-12
@filnor

I'm not completely into everything, but it seems to me that you need this operator https://docs.mongodb.com/manual/reference/operator...
I.e. you will have the following pipeline: $project, $lookup, $unwind, $lookup.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question