Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of partial model from sub document array (MongoDB C# Driver)

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?

like image 422
maor david Avatar asked Nov 08 '22 15:11

maor david


1 Answers

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);
like image 181
Jpst Avatar answered Nov 14 '22 21:11

Jpst