在 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 }
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP