2016-09-01 2 views
0

내 문서는 다음과 같다 :고유 배열 요소는

{ 
    "_id": "1", 
    "tags": [ 
     { "code": "01-01", "type": "machine" }, 
     { "code": "04-06", "type": "gearbox" }, 
     { "code": "07-01", "type": "machine" } 
    ] 
}, 
{ 
    "_id": "2", 
    "tags": [ 
     { "code": "03-04","type": "gearbox" }, 
     { "code": "01-01", "type": "machine" }, 
     { "code": "04-11", "type": "machine" } 
    ] 
} 

가 난 단지 유형이 "기계"입니다 태그에 대해 별개의 코드를 얻으려면. 위의 예에서 결과는 ["01-01", "07-01", "04-11"]이어야합니다. 어떻게해야합니까? 당신이 그 (것)들을 하나의 문서 내에서 배열에 넣고 싶은 경우에,

db.collection_name.aggregate([ 
    { 
     $unwind: "$tags" 
    }, 
    { 
     $match: { 
      "tags.type": "machine" 
     } 
    }, 
    { 
     $group: { 
      _id: "$tags.code" 
     } 
    }, 
    { 
     $project:{ 
      _id:false 
      code: "$_id" 
     } 
    } 
]); 

을 또는 : 키가 결과 집합에 당신에게 별도의 문서에서 각 태그를 줄 것 같은 태그로 $unwind 다음 $group을 사용

+0

[mongoDB 컬렉션에서 배열을 얻는 방법] 가능한 복제본입니다. (http://stackoverflow.com/questions/38210121/how-to-get-array-from-mongodb-collection) – styvane

답변

1

, 당신은 두 번째 $group 단계에서 $push를 사용할 수 있습니다

db.collection_name.aggregate([ 
    { 
     $unwind: "$tags" 
    }, 
    { 
     $match: { 
      "tags.type": "machine" 
     } 
    }, 
    { 
     $group: { 
      _id: "$tags.code" 
     } 
    }, 
    { 
     $group:{ 
      _id: null, 
      codes: {$push: "$_id"} 
     } 
    } 
]); 

다른 사용자가 { $match: { "tags.type": "machine" } }의 초기 단계를 포함하여 제안했다. 데이터에 "기계" 태그가 포함되지 않은 상당수의 문서가 포함될 가능성이있는 경우 좋은 방법입니다. 그렇게하면 해당 문서를 불필요하게 처리하지 않아도됩니다. 파이프 라인은 다음과 같이 보일 것이다 :

db.collection_name.aggregate([ 
    { 
     $match: { 
      "tags.type": "machine" 
     } 
    }, 
    { 
     $unwind: "$tags" 
    }, 
    { 
     $match: { 
      "tags.type": "machine" 
     } 
    }, 
    { 
     $group: { 
      _id: "$tags.code" 
     } 
    }, 
    { 
     $group:{ 
      _id: null, 
      codes: {$push: "$_id"} 
     } 
    } 
]); 
+0

나는 선두로 제안 할 것입니다. '{$ match : { "tags.type": "machine"}}'을 사용하여 기여하지 않을 문서를 제거하십시오. – cdbajorin

+0

좋습니다. 답변을 업데이트했습니다. – Wake

1
> db.foo.aggregate([ 
... { $unwind : "$tags" }, 
... { $match : { "tags.type" : "machine" } }, 
... { $group : { "_id" : "$tags.code" } }, 
... { $group : { _id : null , "codes" : {$push : "$_id"} }} 
... ]) 
{ "_id" : null, "codes" : [ "04-11", "07-01", "01-01" ] } 
1

더 좋은 방법tags.type에 직접 그룹에하고 tags.codeaddToSet을 사용합니다.

db.name.aggregate([ 
    {$unwind:"$tags"}, 

    {$match:{"tags.type":"machine"}}, 

    {$group:{_id:"$tags.type","codes":{$addToSet:"$tags.code"}}} 
]) 

출력 : : 여기

우리가 통합의 3 단계에 동일한 출력을 달성 할 수있는 방법은 { "_id": "기계", "코드"[ "04-11", "07 -01 ","01-01 "]}

또한 tag.type 코드를 필터링하려면 일치 단계에서"machine "을 원하는 tag.type으로 바꾸면됩니다.