I'm trying to receive new array with only sub fields filled using MongoDB C# Driver. For example I have the following document:
{
"_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
}
]
}
I'm trying to receive document with new array of CartItems
with only ProductId
so the response will look like:
{
"_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
}
]
}
The projection I tried (using C#) was
ProjectionDefinition<Cart, Cart> projectionDefinition = Builders<Cart>.Projection.Include(doc => doc.CartItems[0].ProductId) .Exclude(doc => doc.Id);
But the result is CartItems
array with all default values (include ProductId
). What I do wrong?
According to the documentation:
Use the dot notation to refer to the embedded field
https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-specific-fields-in-embedded-documents
So your projection should look like this:
Builders<Cart>.Projection
.Include("CartItems.ProductId")
.Exclude(doc => doc.Id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With