簡體   English   中英

使用聚合,匹配和查找,使用MongoDB一次查詢多個集合

[英]Query multiple collections at once with MongoDB using aggregate, match and lookup

我在這里遇到了一個問題,因為在通過多個集合進行查詢時,我試圖用$ lookup來解決問題,如此處所述: https : //stackoverflow.com/a/43653679和此處: https//docs.mongodb.com/manual/reference/operator/aggregation/lookup/

有3個收藏:

用戶 -可以在哪里使用“ 電子郵件 ”字段

配置 -在哪里可以使用' vpn '字段

固件 -可以在何處使用“ 版本 ”字段


我的目的是計算符合以下條件的用戶數量:

  • 電子郵件 =! @ yahoo.com,@ gmail.com,@ hotmail.com
  • VPN已開啟
  • 版本是123

您能幫我了解我的查詢外觀嗎? 非常感謝!

我現在不在我的工作站上,但是我相信這是您想要的。

您在問題中上面已解決的鏈接可以完美地說明您要做什么,似乎您很難解決(我們都做到了。我知道很多事)

為了將來參考,通常會將其視為/標記為您所參考問題的副本,但我發現您是新來的,出於某種原因,我的心情很好。 希望這會有所幫助,如果沒有讓我知道! 歡迎來到社區!

db.Users.aggregate([
    { $match: { email: "test@somemail.com" } }, #Get the users that match the email constraints
    {
        $lookup: { #Get the config document associated to the/each user
            from: "Config",
            localField: "config_id",
            foreignField: "_id",
            as: "config"
        }
    },
    {
        $match: { #limit the configs with VPNs that are "ON"
            "config.vpn": "ON"
        }
    },
    {
        $lookup: { #Get the Firmware associated to the/each User
            from: "Firmware",
            localField: "firmware_id",
            foreignField: "_id",
            as: "firmware"
        }
    },
    {   
        $match: { #Limit to only firmwares that are version 123
               "firmware.version": 123
        }
    },
    $count: { "_id" }
])

從理論上講,這將返回如下文檔:

 { "_id": <the number of Users with specified "email", "vpn", "version"> }

我最終使用了js腳本。 這是大多數:

let vpnConfigs = dbRefs.Devices.VpnConfig.find({"vpn": "on"}).toArray() 
let firmwareConfigs = dbRefs.Devices.FirmwareConfig.find({"version": "1.2.1"}).toArray()

let tenants = dbRefs.Users.Tenant.find().toArray()

let filteredDevices = vpnConfigs.filter(   vpnConfigModel => firmwareConfigs.some(firmwareConfigModel => vpnConfigModel.parent.id
=== firmwareConfigModel.parent.id) )

let totalDevicesNumber = 0

let filteredTenants = tenants.filter(
    tenant => {
        if(/@psft\.com|@gmail\.com|@yahoo\.com|@maildrop.cc/.test(tenant.ownerEmail)){
            return false;
        }

        return filteredDevices.some(configModel => configModel.tenantId === tenant._id)
        let devicesCount = filteredDevices.filter(configModel => configModel.tenantId === tenant._id).length
        totalDevicesNumber += devicesCount
        return devicesCount > 0
    } )

filteredTenants.map(
    tenant => print(tenant.ownerEmail) )


print(`Found ${filteredTenants.length} tenant(s)`) 
print(`Found ${totalDevicesNumber} device(s)`)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM