在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 }热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短