Mongo C#驱动程序使用elemMatch时如何从投影中排除元素?

时间:2018-12-28 11:32:12

标签: c# mongodb

我有一个名为“交易”的集合。这是集合的结构:

{
 "TradeId": 1234,
 "Products": [
  {
     "Name": "Test product",
     "Offers": [
        {
           "SupplierName": "John Smith",
           "OfferPrice": 12345.6
        }],
     "Requests": [
        {
           "CustomerName": "Anna Doe",
           "RequestPrice": 28574.5
        }]
   }]
}

我只需要获取指定交易的“要约”数组,即可按产品名称进行过滤。到目前为止,这是我所做的:

            var filteredTrade = await _tradesCollection.Find(
                        x => x.TradeId == 1234)
                    .Project<Trade>(Builders<Trade>.Projection.ElemMatch(
                        x => x.Products,
                        i => i.Name == "Test product"))
                    .SingleOrDefaultAsync();

这将按预期过滤产品名称。但是,查询还会获取整个请求集合。有什么办法可以使 only 仅提供报价集合或以某种方式排除请求集合?

1 个答案:

答案 0 :(得分:1)

您需要使用Aggregation Framework来投影具有多层嵌套数组的文档。在mongo shell中,您可以尝试以下代码:

db.col.aggregate([
    {
        $match: { TradeId: 1234 }
    },
    {
        $unwind: "$Products"
    },
    {
        $match: { "Products.Name": "Test product" }
    },
    {
        $project: {
            _id: 0,
            Offers: "$Products.Offers"
        }
    }
])

打印:{ "Offers" : [ { "SupplierName" : "John Smith", "OfferPrice" : 12345.6 } ] }

可以转换为以下C#代码(返回类型Product的列表):

var project = new BsonDocumentProjectionDefinition<BsonDocument>(
    BsonDocument.Parse("{ Offers: \"$Products.Offers\", _id: 0 }"));

var q = Col.Aggregate()
            .Match(x => x.TradeId == 1234)
            .Unwind<Trade>(x => x.Products)
            .Match(x => x["Products.Name"] == "Test product")
            .Project(project)
            .As<Product>()
            .ToList();