从子文档数组获取部分模型数组(MongoDB C#驱动程序)

mao*_*vid 5 c# mongodb mongodb-.net-driver

我正在尝试接收仅使用MongoDB C#驱动程序填充的子字段的新数组。例如,我有以下文档:

{
    "_id" : "fca739d0-cddd-4762-b680-597d2996404b",
    "Status" : 1,
    "AccountId" : "1112",
    "Timestamp" : ISODate("2016-04-27T13:46:01.888Z"),
    "CartItems" : [ 
        {
            "ProductId" : "222",
            "Price" : 100,
            "ShippingPrice" : 20,
            "Quantity" : 3
        }, 
        {
            "ProductId" : "504",
            "Price" : 200,
            "ShippingPrice" : 20,
            "Quantity" : 2
        }, 
        {
            "ProductId" : "504",
            "Price" : 200,
            "ShippingPrice" : 20,
            "Quantity" : 1
        }, 
        {
            "ProductId" : "504",
            "Price" : 200,
            "ShippingPrice" : 20,
            "Quantity" : 1
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试CartItems仅接收具有的新数组的文档,ProductId因此响应如下所示:

{
    "_id" : null,
    "Status" : 0,
    "AccountId" : null,
    "Timestamp" : ISODate("2016-04-27T13:46:01.888Z"), (**default)
    "CartItems" : [ 
        {
            "ProductId" : "222",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }, 
        {
            "ProductId" : "504",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }, 
        {
            "ProductId" : "504",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }, 
        {
            "ProductId" : "504",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我尝试的投影(使用C#)是

ProjectionDefinition<Cart, Cart> projectionDefinition = Builders<Cart>.Projection.Include(doc => doc.CartItems[0].ProductId)                                                                                      .Exclude(doc => doc.Id);
Run Code Online (Sandbox Code Playgroud)

但是结果是CartItems具有所有默认值(包括ProductId)的数组。我做错了什么?

Tsa*_*nas 1

根据文档:

使用点符号来引用嵌入字段

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-specific-fields-in-embedded-documents

所以你的投影应该是这样的:

Builders<Cart>.Projection
.Include("CartItems.ProductId")
.Exclude(doc => doc.Id);
Run Code Online (Sandbox Code Playgroud)