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 badges1 Answer
Reset to default 2Your 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
版权声明:本文标题:c# - MongoDB - Count number of object in array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741600538a2387674.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论