미니옵빠의 code stubs

MongoDB aggregate + unwind + out 조합에서 duplicate ID 오류를 만날 경우 본문

Database/MongoDB

MongoDB aggregate + unwind + out 조합에서 duplicate ID 오류를 만날 경우

미니옵빠 2019. 1. 19. 16:59

MongoDB aggregate + unwind + out 조합에서 duplicate ID 오류를 만날 경우


projection 시 _id 를 없애면 됨.


$out 으로 생성되는 신규 collection 의 PK 로 기존 문서의 _id 가 입력되다보니, unwind 로 array field 가 deconstructs 되었을 때 (left join 처럼) 중복 키가 발생됨. 그래서 _id 를 제거해 버리면, 신규 collection 내 신규 _id 가 생성되어 중복 오류가 사라짐



예) 기존 _id -> id 로 대체하고, _id 필드는 지움


.aggregate([

{

  $project: {

    id: '$_id',

    _id: 0,

  }

},

{

  $unwind: { ... }

},

{

  $out: 'tempCollection'

},

])