获取 MongoDB 中特定值的计数
mongodbdatabasebig data analytics更新于 2026/1/11 12:22:17
要获取 MongoDB 中特定值的计数,请使用 aggregate()。让我们创建一个包含文档的集合 −
> db.demo210.insertOne(
... {
... details: [
... {
... ClientName: "Robert"
... },
... {
...
... lientName: "John Doe"
... },
... {
...
... ClientName: "Robert"
... },
... {
...
... ClientName: "Robert"
... },
... {
...
... ClientName: "David Miller"
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3d99ab03d395bdc21346f9")
}
借助 find() 方法显示集合中的所有文档 −
> db.demo210.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "details" : [ { "ClientName" : "Robert" }, { "ClientName" : "John Doe" }, { "ClientName" : "Robert" }, { "ClientName" : "Robert" }, { "ClientName" : "David Miller" } ] }
以下是获取特定值计数的查询 −
> db.demo210.aggregate([
... { "$match" : { "details.ClientName" : "Robert" } },
... { "$unwind" : "$details" },
... { "$match" : { "details.ClientName" : "Robert" } },
... { "$group" : { "_id" : "$_id", "Size" : { "$sum" : 1 } } },
... { "$match" : { "Size" : { "$gte" : 2 } } }
...]);
这将产生以下输出 −
{ "_id" : ObjectId("5e3d99ab03d395bdc21346f9"), "Size" : 3 }

