如何對 MongoDB 中的兩個列進行分組?
要對兩列進行分組,請使用 $lookup。讓我們建立一個含有文件的集合 −
> db.demo132.insertOne({"CountryName1":"US","CountryName2":"UK",Value:50});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31950468e7f832db1a7f75")
}
> db.demo132.insertOne({"CountryName1":"UK","CountryName2":"AUS",Value:10});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31951d68e7f832db1a7f76")
}
> db.demo132.insertOne({"CountryName1":"AUS","CountryName2":"US",Value:40});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31952c68e7f832db1a7f77")
}使用 find() 方法顯示集合中的所有文件 −
> db.demo132.find();
這將生成以下輸出 −
{ "_id" : ObjectId("5e31950468e7f832db1a7f75"), "CountryName1" : "US", "CountryName2" : "UK", "Value" : 50 }
{ "_id" : ObjectId("5e31951d68e7f832db1a7f76"), "CountryName1" : "UK", "CountryName2" : "AUS", "Value" : 10 }
{ "_id" : ObjectId("5e31952c68e7f832db1a7f77"), "CountryName1" : "AUS", "CountryName2" : "US", "Value" : 40 }以下是在 MongoDB 中對兩列進行分組的查詢 −
> db.demo132.aggregate( [
... {
... "$lookup" : {
... "from" : "demo132",
... "localField" : "CountryName1",
... "foreignField" : "CountryName2",
... "as" : "out"
... }
... },
... {
... "$unwind" : "$out"
... },
... {
... "$project" : {
... "_id" : 0,
... "CountryName1" : 1,
... "total" : { "$sum" : [ "$Value", "$out.Value"]}
... }
... }
... ])這將生成以下輸出 −
{ "CountryName1" : "US", "total" : 90 }
{ "CountryName1" : "UK", "total" : 60 }
{ "CountryName1" : "AUS", "total" : 50 }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP