MongoDb C#:获取所有匹配的子文档

时间:2018-09-21 16:32:44

标签: c# mongodb mongodb-query aggregation-framework mongodb-.net-driver

假设我具有以下商家文档结构

商人

[
   {
      "ID":"1",
      "Name":"Merchant 1",
      "Vendors":[
         {
            "ID":"1",
            "Name":"Vendor 1",
            "Currency":"GBP"
         },
         {
            "ID":"2",
            "Name":"Vendor 2",
            "Currency":"EURO"
         },
         {
            "ID":"3",
            "Name":"Vendor 3",
            "Currency":"GBP"
         }
      ]
   },
   {
      "ID":"2",
      "Name":"Merchant 2",
      "Vendors":[
         {
            "ID":"4",
            "Name":"Vendor 4",
            "Currency":"GBP"
         },
         {
            "ID":"5",
            "Name":"Vendor 5",
            "Currency":"EURO"
         },
         {
            "ID":"6",
            "Name":"Vendor 6",
            "Currency":"GBP"
         }
      ]
   }
]

现在,我想获得ID为2的商人以及货币为GBP的所有卖方。

输出应为

{
      "ID":"2",
      "Name":"Merchant 2",
      "Vendors":[
         {
            "ID":"4",
            "Name":"Vendor 4",
            "Currency":"GBP"
         },
         {
            "ID":"6",
            "Name":"Vendor 6",
            "Currency":"GBP"
         }
      ]
   }

我如何在mongodb和C#中使用.Find方法执行此操作?

我正在考虑聚合框架,但我不能仅仅使其发挥作用。

1 个答案:

答案 0 :(得分:0)

db.Merchants.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $match: {
                "ID": "2"
            }
        },

        // Stage 2
        {
            $project: {
                ID: 1,
                Name: 1,
                Vendors: {
                    $filter: {
                        input: "$Vendors",
                        as: "vendor",
                        cond: {
                            $eq: ["$$vendor.Currency", "GBP"]
                        }
                    }
                }
            }
        },

    ]



);