Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB의 두 열에 걸쳐 그룹화하시겠습니까?

<시간/>

두 열에 걸쳐 그룹화하려면 $lookup을 사용하십시오. 문서로 컬렉션을 만들자 −

> db.demo132.insertOne({"CountryName1":"US","CountryName2":"UK",Value:50});{ "승인됨":true, "insertedId":ObjectId("5e31950468e7f832db1a7f75") }> db.demo132.insertOne({"CountryName1":"UK","CountryName2":"AUS",Value:10});{ "승인됨":true, "insertedId":ObjectId("5e31951d68e7f832db1a7f76") db.demo132.insertOne({"CountryName1":"AUS","CountryName2":"US",Value:40});{ "승인됨":true, "insertedId":ObjectId("5e31952c68e7f832db1a7f77")}

find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -

> db.demo132.find();

이것은 다음과 같은 출력을 생성합니다 -

{ "_id":ObjectId("5e31950468e7f832db1a7f75"), "CountryName1":"미국", "CountryName2":"UK", "값":50) }{ "_id":ObjectId("5e31951d68e7f83 CountryName1":"UK", "CountryName2":"AUS", "Value":10 }{ "_id":ObjectId("5e31952c68e7f832db1a7f77"), "CountryName1":"AUS", "CountryName2":"US", " 값" :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 .값"]}... }... }... ])

이것은 다음과 같은 출력을 생성합니다 -

{ "CountryName1" :"US", "total" :90 }{ "CountryName1" :"UK", "total" :60 }{ "CountryName1" :"AUS", "total" :50 }