MongoDB中获取特定值的计数

要获取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 }