在 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 }

更新於: 27-Mar-2020

364 次瀏覽

開啟你的職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.