MongoDB의 $unwind는 입력 문서에서 배열 필드를 분해하여 각 요소에 대한 문서를 출력합니다. 집계()와 함께 $unwind를 사용하여 개수를 가져옵니다. 문서로 컬렉션을 만들자 −
> db.demo478.insertOne(
... {
...
... "Details" : {
... _id:1,
... "Information" : [
... {
... "Name" : "Chris",
... "Age":21
... },
... {
... "Name" : "David",
... "Age":23
... },
... {
...
... "Name" : null,
... "Age":22
... },
... {
...
... "Name" : null,
... "Age":24
... }
... ]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8204acb0f3fa88e2279092")
}
>
> db.demo478.insertOne(
... {
...
... "Details" : {
... _id:2,
... "Information" : [
... {
... "Name" : "Bob",
... "Age":21
... },
... {
... "Name" : null,
... "Age":20
... }
... ]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8204adb0f3fa88e2279093")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo478.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e8204acb0f3fa88e2279092"), "Details" : { "_id" : 1, "Information" : [ {
"Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : null, "Age" : 22 }, {
"Name" : null, "Age" : 24 } ] } }
{ "_id" : ObjectId("5e8204adb0f3fa88e2279093"), "Details" : { "_id" : 2, "Information" : [ {
"Name" : "Bob", "Age" : 21 }, { "Name" : null, "Age" : 20 } ] } } 다음은 카운트를 얻기 위해 $unwind를 구현하는 쿼리입니다 -
> db.demo478.aggregate([
... { "$unwind": "$Details.Information" },
... {
... "$group" : {
... "_id": "$Details.Information.Age",
... "count" : {
... "$sum": {
... "$cond": [
... { "$gt": [ "$Details.Information.Name", null ] },
... 1, 0
... ]
... }
... }
... }
... },
... { "$sort" : { "count" : -1 } }
... ]) 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : 21, "count" : 2 }
{ "_id" : 23, "count" : 1 }
{ "_id" : 24, "count" : 0 }
{ "_id" : 20, "count" : 0 }
{ "_id" : 22, "count" : 0 }