Home > OS >  Mongodb aggregation. I need to filter results that matches within multiple arrays
Mongodb aggregation. I need to filter results that matches within multiple arrays

Time:05-05

I have this one query that takes to $in parameter different arrays. One is openBehaviourIds, second is closeBehaviours. I would like to avoid duplicated code and make one query with aggregation to get result as {openBehaviours: [{}, {}...], closeBehaviours: [{},{},{}...]} istead of using:

  1. const openBehaviours = await behavioursCollection.aggregate([...])
  2. const closeBehaviours = await behavioursCollection.aggregate([...])

open and close behaviourIds are arrays of strings

Full query for to get both behaviours below (almost the same):

const openBehaviours = await behavioursCollection.aggregate([
            { $match: { 'behaviourId': { $in: openBehaviourIds } } }, {
                $lookup: {
                    from: 'colors',
                    localField: 'domainId',
                    foreignField: 'domainId',
                    as: 'color'
                }
            }, { $unwind: '$color' }
        ], { session }).toArray()

const closeBehaviours = await behavioursCollection.aggregate([
            { $match: { 'behaviourId': { $in: closeBehaviours } } }, {
                $lookup: {
                    from: 'colors',
                    localField: 'domainId',
                    foreignField: 'domainId',
                    as: 'color'
                }
            }, { $unwind: '$color' }
        ], { session }).toArray()

How could I merge this to one query to make it crystal clear? Thanks for help

CodePudding user response:

you can use $facet operator to achieve that.

behavioursCollection.aggregate([
{$facet:{
    "openBehaviours":[
        { $match: { 'behaviourId': { $in: openBehaviourIds } } },
        {
            $lookup: {
                from: 'colors',
                localField: 'domainId',
                foreignField: 'domainId',
                as: 'color'
            }
        },
        { $unwind: '$color' }
    ],
    "closeBehaviours":[
        { $match: { 'behaviourId': { $in: closeBehaviours  } } },
        {
            $lookup: {
                from: 'colors',
                localField: 'domainId',
                foreignField: 'domainId',
                as: 'color'
            }
        },
        { $unwind: '$color' }   
    ]
}}]);
  • Related