programing

MongoDB - 집계를 사용하여 배열 해제 및 중복 제거

iphone6s 2023. 5. 7. 11:17
반응형

MongoDB - 집계를 사용하여 배열 해제 및 중복 제거

MongoDB Aggregation Framework를 사용하여 어레이를 풀고 있는데 어레이에 중복 항목이 있으므로 그룹화를 진행하는 동안 해당 중복 항목을 무시해야 합니다.

어떻게 하면 그것을 달성할 수 있을까요?

$addToSet을 사용하여 다음 작업을 수행할 수 있습니다.

db.users.aggregate([
  { $unwind: '$data' },
  { $group: { _id: '$_id', data: { $addToSet: '$data' } } }
]);

실제 질문을 보지 않고는 더 구체적인 답변을 드리기 어렵습니다.

$addToSet을 사용해야 하지만 처음에는 _id로 그룹화해야 합니다. 그렇지 않으면 목록의 항목당 요소를 얻을 수 있기 때문입니다.

다음과 같은 문서가 있는 수집 게시물을 상상해 보십시오.

{
     body: "Lorem Ipsum...", 
     tags: ["stuff", "lorem", "lorem"],
     author: "Enrique Coslado"
}

작성자당 가장 일반적인 태그를 계산하려고 합니다.다음과 같은 집계 쿼리를 만들 수 있습니다.

db.posts.aggregate([
    {$project: {
        author: "$author", 
        tags: "$tags", 
        post_id: "$_id"
    }}, 

    {$unwind: "$tags"}, 

    {$group: {
        _id: "$post_id", 
        author: {$first: "$author"}, 
        tags: {$addToSet: "$tags"}
    }}, 

    {$unwind: "$tags"},

    {$group: {
        _id: {
            author: "$author",
            tags: "$tags"
        },
        count: {$sum: 1}
    }}
])

이렇게 하면 다음과 같은 문서를 얻을 수 있습니다.

{
     _id: {
         author: "Enrique Coslado", 
         tags: "lorem"
     },
     count: 1
}

이전 답변이 올바르지만 다음을 수행하는 절차$unwind -> $group -> $unwind단순화할 수 있습니다.사용할 수 있습니다.$addFields+$reduce이미 고유한 항목을 포함하는 필터링된 배열을 파이프라인으로 전달한 다음$unwind단 한 번

예제 문서:

{
     body: "Lorem Ipsum...", 
     tags: [{title: 'test1'}, {title: 'test2'}, {title: 'test1'}, ],
     author: "First Last name"
}

쿼리:

db.posts.aggregate([
    {$addFields: {
        "uniqueTag": {
            $reduce: {
                input: "$tags",
                initialValue: [],
                in: {$setUnion: ["$$value", ["$$this.title"]]}
            }
        }
    }}, 

    {$unwind: "$uniqueTag"}, 

    {$group: {
        _id: {
            author: "$author",
            tags: "$uniqueTag"
        },
        count: {$sum: 1}
    }}
])

언급URL : https://stackoverflow.com/questions/18804404/mongodb-unwind-array-using-aggregation-and-remove-duplicates

반응형