sql >> Base de Datos >  >> NoSQL >> MongoDB

Filtre las matrices duplicadas y devuelva la matriz única en la agregación de mongodb

db.collection.aggregate([
  {//Denormalize first level
    "$unwind": "$newList"
  },
  {//Second nested level
    "$unwind": "$newList.newPMBList"
  },
  {//Deep nested last level
    "$unwind": "$newList.newPMBList.newPMList"
  },
  {
    $group: {//Grouping back
      "_id": null,
      "newList": {
        $push: "$newList.newPMBList.newPMList"
      }
    }
  },
  {
    $project: {//Finding unique
      newList: {
        $setUnion: [
          "$newList",
          "$newList"
        ]
      }
    }
  }
])

Le sugiero que incluya otros campos usando first acumulador en group y conservarlos en project .

Puede simplificar aún más como se muestra a continuación

db.test.aggregate([
  {
    "$unwind": "$newList"
  },
  {
    "$unwind": "$newList.newPMBList"
  },
  {
    "$unwind": "$newList.newPMBList.newPMList"
  },
  {
    $group: {
      "_id": null,
      "newList": {//addToSet keeps distinct
        $addToSet: "$newList.newPMBList.newPMList"
      }
    }
  }
])

Además, compre omitiendo una desnormalización, pero devuelve una matriz de matrices.

db.test.aggregate([
  {
    "$unwind": "$newList"
  },
  {
    "$unwind": "$newList.newPMBList"
  },
  {
    $group: {
      "_id": null,
      "newList": {
        $addToSet: "$newList.newPMBList.newPMList"
      }
    }
  }
])

Si omite otro nivel, agregará un nivel anidado más en el resultado.