计算mongodb c#LINQ中的嵌入文档数
您好,我正在尝试使用LINQ对数组中的文档进行计数 我的结构很简单。这是一个简化的Bson示例计算mongodb c#LINQ中的嵌入文档数,c#,mongodb,linq,mongodb-.net-driver,C#,Mongodb,Linq,Mongodb .net Driver,您好,我正在尝试使用LINQ对数组中的文档进行计数 我的结构很简单。这是一个简化的Bson示例 { "_id" : ObjectId("56fa945dbf0c37096048109f"), "Commands" : [ { "CommandId" : ObjectId("56fbdc24bf0c372078f10227"), }, { "CommandId" : ObjectId("56fbdc28bf0c372078f1022b"
{
"_id" : ObjectId("56fa945dbf0c37096048109f"),
"Commands" : [
{
"CommandId" : ObjectId("56fbdc24bf0c372078f10227"),
},
{
"CommandId" : ObjectId("56fbdc28bf0c372078f1022b"),
},
{
"CommandId" : ObjectId("570b6863bf0c370838473321"),
}
]
}
这是我到目前为止提出的,但它只说我有一个命令
var result =
(from e in collection.AsQueryable<Sequence>()
where e._id == seqid
select e.Commands).Count();
Console.WriteLine("There where " + result + " Commands");
var结果=
(来自collection.AsQueryable()中的e)
其中e._id==seqid
选择e.Commands).Count();
Console.WriteLine(“那里有“+result+”命令”);
有什么想法吗?我设法想出了一个解决方案,不确定它是否是最好的,但它确实有效
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");
我设法想出了一个解决方案,不确定它是否是最好的,但它是有效的
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");
我建议为此使用聚合框架和$size,这样可以避免将阵列本身传输到客户端 例如:
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");
您可以在此处阅读有关$size的更多信息:
我建议为此使用聚合框架和$size,这样可以避免将阵列本身传输到客户端 例如:
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");
您可以在此处阅读有关$size的更多信息:
LINQ查询始终转换为聚合框架管道
> var pipeline = [
... { "$group" : { "_id" : 1, "__result" : { "$sum" : 1 } } }
... ]
> db.test.aggregate(pipeline)
使用简单计数方法进行筛选LINQ查询始终转换为聚合框架管道
> var pipeline = [
... { "$group" : { "_id" : 1, "__result" : { "$sum" : 1 } } }
... ]
> db.test.aggregate(pipeline)
使用简单计数方法进行过滤我已经有一段时间没有使用MongoDB了,但是看起来您正在计算Commands对象的数量,在本例中,这实际上只是一项。您需要枚举Commands对象的内容。我已经有一段时间没有使用MongoDB了,但是看起来您正在计算Commands对象的数量,在本例中,实际上只有1项。您需要枚举Commands对象的内容。我不知道这个。看起来不错,很有效谢谢你,凯文!我不知道那件事。看起来不错,很有效谢谢你,凯文!