2

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?

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thank you for your answer, is there a good practive in the request to the database. Should I try to isolate the answer of the databasse to be the smallest necessary or to simplify the request as much as possible?
Hmm, sounds like an opinion-based. From what I understand from your comment, do you mean to simplify the query executed in the DB? From my perspective, the simplification in terms of reducing and only returning necessary data; avoids the complex computation to improve the query performance.
My thinking is that I dont need the whole object from the base to have the count. From my understanding, the 'collection.Find(x=>x.Id==id).First()' return the whole object and then we filter the articles and the count. But if the array length is counted directly in the database it should be optimal. Maybe it's opinion-based....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.