admin管理员组

文章数量:1296310

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?

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?

Share edited Feb 13 at 23:36 Yong Shun 51.4k6 gold badges35 silver badges63 bronze badges asked Feb 12 at 12:25 RiddsawRiddsaw 231 silver badge4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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;

本文标签: cMongoDBCount number of object in arrayStack Overflow