从子文档数组(MongoDB C#驱动程序)获取部分模型的数组
我正在尝试接收使用MongoDB C#Driver只填充子字段的新数组。例如,我有以下文档:从子文档数组(MongoDB C#驱动程序)获取部分模型的数组,c#,mongodb,mongodb-.net-driver,C#,Mongodb,Mongodb .net Driver,我正在尝试接收使用MongoDB C#Driver只填充子字段的新数组。例如,我有以下文档: { "_id" : "fca739d0-cddd-4762-b680-597d2996404b", "Status" : 1, "AccountId" : "1112", "Timestamp" : ISODate("2016-04-27T13:46:01.888Z"), "CartItems" : [ { "Produc
{
"_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
}
]
}
我正在尝试使用新的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
}
]
}
我尝试的投影(使用C#)是
ProjectionDefinition ProjectionDefinition=Builders.Projection.Include(doc=>doc.CartItems[0].ProductId).Exclude(doc=>doc.Id);
但是结果是带有所有默认值(包括
ProductId
)的CartItems
数组。我做错了什么?根据文档:
使用点符号表示嵌入字段
所以你的投影应该是这样的:
Builders<Cart>.Projection
.Include("CartItems.ProductId")
.Exclude(doc => doc.Id);
Builders.Projection
.包括(“CartItems.ProductId”)
.Exclude(doc=>doc.Id);
Builders<Cart>.Projection
.Include("CartItems.ProductId")
.Exclude(doc => doc.Id);