簡體   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