简体   繁体   中英

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
                                }
                            }
                        }
                    ]
                }
            }])

Maybe with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM