Jacob
Jacob

Reputation: 381

Count embedded documents mongodb c# LINQ

Hello I am trying to count my documents in an array using LINQ.

My structure is simple. Here is a simplified Bson sample.

{
"_id" : ObjectId("56fa945dbf0c37096048109f"),
"Commands" : [ 
    {

        "CommandId" : ObjectId("56fbdc24bf0c372078f10227"),
    }, 
    {
        "CommandId" : ObjectId("56fbdc28bf0c372078f1022b"),      
    }, 
    {
        "CommandId" : ObjectId("570b6863bf0c370838473321"),
    }
]

}

This is what I have come up with so far but it only says i have 1 command.

    var result =
                     (from e in collection.AsQueryable<Sequence>()
                     where e._id == seqid
                     select e.Commands).Count();               
                Console.WriteLine("There where " + result + " Commands");

Any ideas?

Upvotes: 0

Views: 1540

Answers (3)

ZOXEXIVO
ZOXEXIVO

Reputation: 960

LINQ queries are always translated to aggregation framework pipelines

> var pipeline = [
... { "$group" : { "_id" : 1, "__result" : { "$sum" : 1 } } }
... ]
> db.test.aggregate(pipeline)

Use simple Count method with filtering

Upvotes: 0

Kevin Blake
Kevin Blake

Reputation: 444

I would recommend using the aggregation framework and $size for this - that will avoid transferring the array itself to the client.

For example:

var result = collection.Aggregate().Match(x => x.Id == seqid)
    .Project(new BsonDocument("count", new BsonDocument("$size", "$Commands")))
    .FirstOrDefault()
    .GetValue("count").ToInt32();

Console.WriteLine("There were " + result + " Commands");

You can read more about $size here: https://docs.mongodb.org/manual/reference/operator/aggregation/size/

Upvotes: 2

Jacob
Jacob

Reputation: 381

I managed to come up with a solution, not sure if it's the best but it works.

            var result = (from p in collection.AsQueryable().Where(p => p._id == seqid)
                 from cmds in p.Commands
                 select cmds).Count();
            Console.WriteLine("There where " + result + " Commands");

Upvotes: 0

Related Questions