найти дубликаты в массиве для каждого документа в mongodb - PullRequest
0 голосов
/ 29 января 2020

Допустим, у меня есть какой-то документ с такой структурой:

   _id: ObjectId('444455'),
   name: 'test',
   email: 'email,
   points: {
      spendable: 23,
      history: [
          {
             comment: 'Points earned by transaction #1234',
             points: 1
          },
          {
             comment: 'Points earned by transaction #456',
             points: 3
          },
          {
             comment: 'Points earned by transaction #456',
             points: 3
          }
      ]
   }
}

Теперь у меня проблема с тем, что некоторые документы содержат дубликаты объектов в массиве points.history.

Есть ли способ легко найти все эти дубликаты по запросу?

Я уже пробовал этот запрос: Найти дубликаты записей в MongoDB , но это показывает общее количество каждой дублированной строки во всех документах. Мне нужен обзор дубликатов для каждого документа, как это:

{
    _id: ObjectId('444455') //_id of the document not of the array item itself
    duplicates: [
       {
        comment: 'Points earned by transaction #456
       }
    ]
}, {
    _id: ObjectId('444456') //_id of the document not of the array item itself
     duplicates: [
         {
            comment: 'Points earned by transaction #66234
         },
         {
            comment: 'Points earned by transaction #7989
         }
     ]
}

Как мне этого добиться?

1 Ответ

2 голосов
/ 29 января 2020

Попробуйте ниже совокупного конвейера

collectionName.aggregate([
  {
    $unwind: "$points.history"
  },
  {
    $group: {
      _id: {
        id: "$_id",
        comment: "$points.history.comment",
        points: "$points.history.points"
      },
      sum: {
        $sum: 1
      },

    }
  },
  {
    $match: {
      sum: {
        $gt: 1
      }
    }
  },
  {
    $project: {
      _id: "$_id._id",
      duplicates: {
        comment: "$_id.comment"
      }
    }
  }
])
...