繁体   English   中英

如何使用 MongoDB 将多个查询合并为一个查询?

[英]How to combine multiple queries into one query with MongoDB?

给定 3 collections 包含格式

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

我试图通过将三个不同的链接传递给我的 3 collections 来检索 3 个食物列表,例如

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

在哪里

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

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

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

然后,我想将 redFoods、blueFoods 和 greenFoods 组合为一个列表,将食物替换为:

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

如何通过 MongoDB 在一个查询步骤中执行此操作?

到目前为止,我已经尝试过了,但这似乎不起作用:

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

也许与:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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