獲取聚合結果並找出不同 MongoDB\ndocuments 中重複值的計數
要獲得不同文件中重複值的計數,請使用 aggregate()。讓我們建立一個包含文件的集合 -
> db.demo452.insertOne({"StudentName":"John","StudentAge":21});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b7e3371f552a0ebb0a6f3")
}
> db.demo452.insertOne({"StudentName":"John","StudentAge":22});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b7e3671f552a0ebb0a6f4")
}
> db.demo452.insertOne({"StudentName":"John","StudentAge":23});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b7e3971f552a0ebb0a6f5")
}
> db.demo452.insertOne({"StudentName":"David","StudentAge":24});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b7e4371f552a0ebb0a6f6")
}
> db.demo452.insertOne({"StudentName":"David","StudentAge":25});{
"acknowledged" : true,
"insertedId" : ObjectId("5e7b7e4571f552a0ebb0a6f7")
}在集合中使用 find() 方法顯示所有文件 -
> db.demo452.find();
這將產生以下輸出 -
{ "_id" : ObjectId("5e7b7e3371f552a0ebb0a6f3"), "StudentName" : "John", "StudentAge" : 21 }
{ "_id" : ObjectId("5e7b7e3671f552a0ebb0a6f4"), "StudentName" : "John", "StudentAge" : 22 }
{ "_id" : ObjectId("5e7b7e3971f552a0ebb0a6f5"), "StudentName" : "John", "StudentAge" : 23 }
{ "_id" : ObjectId("5e7b7e4371f552a0ebb0a6f6"), "StudentName" : "David", "StudentAge" : 24}
{ "_id" : ObjectId("5e7b7e4571f552a0ebb0a6f7"), "StudentName" : "David", "StudentAge" : 25}以下是查詢不同 MongoDB 文件中重複值的計數 -
> db.demo452.aggregate([
... {$group: {_id:"$StudentName", count:{$sum:1}}},
... {$sort: {count:-1}},
...
... {$group: {_id:1, StudentName:{$push:{StudentName:"$_id", count:"$count"}}}},
... {$project: {
... first : {$arrayElemAt: ["$StudentName", 0]},
... second: {$arrayElemAt: ["$StudentName", 1]},
... others: {$slice:["$StudentName", 2, {$size: "$StudentName"}]}
... }
... },
...
... {$project: {
... status: [
... "$first",
... "$second",
... {
... StudentName: "New Student Name",
... count: {$sum: "$others.count"}
... }
... ]
... }
... },
...
... {$unwind: "$status"},
... {$project: { _id:0, StudentName: "$status.StudentName", count: "$status.count" }}
... ])這將產生以下輸出 -
{ "StudentName" : "John", "count" : 3 }
{ "StudentName" : "David", "count" : 2 }
{ "StudentName" : "New Student Name", "count" : 0 }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP