A
A
Alexey2021-09-15 21:17:34
MongoDB
Alexey, 2021-09-15 21:17:34

Aggregation from two collections?

Guys, help to form a request. There are two collections with the following document structures

db.xcover
{
    "_id" : ObjectId("5b101caddcab7850a4ba32eb"),
    "connections" : [
        169906699,
        125629607
    ],
    ...other-fields
}

db.dcover
{
    "_id" : 169906699,
    "changed" : true,
    "time" : false,
    ...other-fields
}

connection db.dcover._id in db.xcover.connections

And in essence I need the following, further query pseudocode:
db.dcover.aggregate([
  {
    $match: {
        $or: [{ changed: true }, { time: true }]
    }
  },
  {
    $lookup: {
      from: 'xcover',
      localField: '_id',
      pipeline: [
        { $match: { $expr: { $in: ['$_id',  '$xcover.connections'] } } },
        { $unwind: '$xcover' }
      ],
       as: 'xcover'
     }
  }
])


Those. i want to fetch from dcover where changed or time field is set to true and aggregate with data from xcover in array of connections field which has corresponding dcover document IDs.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2021-09-17
@alekstar79

here is the solution:

db.dcover.aggregate([
     { $match: { $or: [{ changed: true },{ time: true }] } },
     {
         $lookup: {
              from: 'xcover',
              let: { group_id: '$_id' },
              pipeline: [
                 { $match: { $expr: { $in: [ '$$group_id', '$connections' ] }}}
              ],
              as: 'xcovers'
          }
     }
])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question