0

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

1 Answer 1

1

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' }   
    ]
}}]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.