Search code examples
c#arraysmongodbaggregation-frameworkmongodb-.net-driver

MongoDB - Count number of object in array


I'm trying to perform a single request to find the length of an array in a MongoDB document. In MongoDB, it can be done with an aggregation but to no success on my own.

db.mycollection.aggregate([{$project: { count: { $size:"$foo" }}}])

I've simplified the request (a lot) and think it can be optimized using the aggregate.

public int getArticlesCount(int id)
{
    int test = collection.Find(x=>x.Id==id).First().articles.Count;
    return test;
}

Is there any good way in the MongoDB C# to do this request?


Solution

  • Your current approach is not wrong as the query is working with Fluent API/LINQ.

    If you are looking for the solution with Aggregate Fluent:

    return collection.Aggregate()
        .Match(x => x.Id == id)
        .Project(x => new
        {
            Count = x.articles.Count()
        })
        .FirstOrDefault()?.Count ?? 0;
    

    Or if you are facing difficulties in converting the query into Aggregate Fluent, you can provide the query directly:

    PipelineDefinition<Class, BsonDocument> pipline = new BsonDocument[]
    {
        new BsonDocument("$match",
            new BsonDocument("_id", id)),
        new BsonDocument("$project",
            new BsonDocument("count",
                new BsonDocument("$size", "$articles")))
    };
    
    return collection.Aggregate(pipeline)
        .FirstOrDefault()
        ?["count"].AsInt32 ?? 0;