How to combine multiple queries into one query with MongoDB?

Given 3 collections containing the format

collection = {
     "Link":link,
     "foodList":foodItems
}

I am trying to retrieve 3 food lists by passing three different links to my 3 collections, such as

redFoods = collection1.find(redLink)
blueFoods = collection2.find(blueLink)
greenFoods = collection3.find(greenLink)

Where

redFoods = [red1, red2, red3, ... , redN]

blueFoods = [blue1, blue2, blue3, ... , blueN]

greenFoods = [green1, green2, green3, ... , greenN]

Then, I want to combine redFoods, blueFoods, and greenFoods as one list that alternates foods as:

[red1, blue1, green1, red2, blue2, green2, red3, blue3, ... , redN, blueN, greenN]

How can I do this in one query step via MongoDB?

I have tried this so far, but this doesn't seem to work:

redLink = "meat"
blueLink = "fruit"
greenLink = "veggies"
shoesList = redFoods.aggregate([
            {
                '$match': {
                    'Link': {
                        redLink
                    }
                }
            }, {
                '$unionWith': {
                    'coll': 'blueFoods',
                    'pipeline': [
                        {
                            '$match': {
                                'Link': {
                                    blueLink
                                }
                            }
                        }
                    ]
                }
            }, {
                '$unionWith': {
                    'coll': 'greenFoods',
                    'pipeline': [
                        {
                            '$match': {
                                'Link': {
                                    greenLink
                                }
                            }
                        }
                    ]
                }
            }])

1 answer

  • answered 2021-02-24 07:53 Zaven Zareyan

    Maybe with:

    {
        '$match': {
             $or: [
                    { 'Link': redLink }, 
                    { 'Link': blueLink }
                  ]
         }
    }