2016-06-30 5 views
0

와 주 문서에 하위 문서를 병합 내 컬렉션의 샘플 기록이다 :MongoDB를 집계 여기

{ 
    _id:id, 
    pages:{id:id,field:value} 
}, 
{ 
    _id:id, 
    pages:{id:otherId,field:otherValue} 
} 

그러나, 내가 무엇을 달성 싶은 것은 :

{ 
    _id:id, 
    id:id, 
    field:value 
}, 
{ 
    _id:id, 
    id:otherId, 
    field:otherValue 
} 

$project 작업으로 하위 문서를 주 문서로 병합 할 수 있습니까?

+0

원하는 출력으로 나열한 결과가 올바르게 포맷되지 않았습니다. 나는 그것을 성취 할 방법을 모른다. – Tiramisu

+1

@Tiramisu 형식을 업데이트했습니다. – nikoss

+1

'$ unwind' 후 파이프 라인에'{ "$ project": "id": "$ pages.id", "field": "$ pages.field"}}'를 추가하십시오. 배열 – styvane

답변

1

문서의 모양을 변경하려면 $project 단계를 파이프 라인에 추가하고 dot notation을 사용하여 하위 문서의 필드에 액세스해야합니다.

{ "$project": { "id": "$pages.id", "field": "$pages.field" } } 
1

내 접근 방식은 예상 결과에 더 가깝습니다.

내 샘플 데이터

"_id" : 1, 
    "pages" : [ 
      { 
        "_id" : "a", 
        "comment" : "Have a Nice Day" 
      }, 
      { 
        "_id" : "b", 
        "comment" : "Everyday is Beautiful" 
      }, 
      { 
        "_id" : "c", 
        "comment" : "All is Well" 
      }, 
      { 
        "_id" : "d", 
        "comment" : "Nature is wonderful" 
      }, 
      { 
        "_id" : "e", 
        "comment" : "Enjoy the moment" 
      } 
    ] 

db.collection.aggregate를 실행 한 후 ([{$의 언 와인드 : "$ 페이지"}])

"_id" : 1, "pages" : { "_id" : "a", "comment" : "Have a Nice Day" } } 
"_id" : 1, "pages" : { "_id" : "b", "comment" : "Everyday is Beautiful" } } 
"_id" : 1, "pages" : { "_id" : "c", "comment" : "All is Well" } } 
"_id" : 1, "pages" : { "_id" : "d", "comment" : "Nature is wonderful" } } 
"_id" : 1, "pages" : { "_id" : "e", "comment" : "Enjoy the moment" } } 

는 파이프 라인에 $ 그룹을 추가

db.collectiom.aggregate ([{$ unwind : "$ pages"}, {$ group : {_ id : "$ pages"}}]);

"_id" : { "_id" : "e", "comment" : "Enjoy the moment" } } 
"_id" : { "_id" : "d", "comment" : "Nature is wonderful" } } 
"_id" : { "_id" : "c", "comment" : "All is Well" } } 
"_id" : { "_id" : "b", "comment" : "Everyday is Beautiful" } } 
"_id" : { "_id" : "a", "comment" : "Have a Nice Day" } } 

희망 하시겠습니까?

+0

잘 이것은 정확히 내가 무엇을 찾고 있었는지 그것은 내가 할 수있는 방법이없는 것 같아요 메인에 병합되지 않습니다 – nikoss