I want to count and sum all posts in Items. When i query my collection with:
GetCollection().Find(p => p.Type == "Test") i receive this:
[
{
"Type": "Test",
"Items": [
{ "Name": "123", "Id":"123" },
{ "Name": "123", "Id":"123" }
]
},
{
"Type": "Test",
"Items": [
{ "Name": "123", "Id":"123" },
{ "Name": "123", "Id":"123" }
]
}
]
But in this case i want to count all posts in items and the result i want to get is: 4. How can i write a query using MongoDB C# driver to get this?
2
Answers
This is how you can do in mongoDB via aggregation:
Explained:
With small modification you can adapt to C#
Playground
Assume that the result returns the array/list of Entity, you can work with System.Linq by flattening the list and getting the count of
Items
.