Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

297
Vistas
How to filter an array of objects to remove elements based on condition in MongoDB aggregate?

I have a collection of documents ChatRooms in MongoDB that has this (simplified) structure:

{
  _id: ObjectId('4654'),
  messages: [
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-01T00:00:00.000Z')
    },
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-02T00:00:00.000Z')
    },
    {
      user: ObjectId('8888'),
      sentAt: ISODate('2022-03-03T00:00:00.000Z')
    },
  ]
}

What I'm trying to achieve is to filter the messages array inside the aggregate pipeline in order to get an array where the userId is presend just once. The result I'm looking for is (or something similar but the array shouldn't have two elements with the same user id):

{
  _id: ObjectId('4654'),
  messages: [
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-01T00:00:00.000Z')
    },
    {
      user: ObjectId('8888'),
      sentAt: ISODate('2022-03-03T00:00:00.000Z')
    },
  ]
}

Is such a thing possible even? Any help would be much appreciated.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can do this in several different ways, here is an example of how to achieve this using the $reduce operator:

db.collection.aggregate([
  {
    $addFields: {
      messages: {
        $reduce: {
          input: "$messages",
          initialValue: [],
          in: {
            $cond: [
              {
                $in: [
                  "$$this.user",
                  "$$value.user"
                ]
              },
              "$$value",
              {
                "$concatArrays": [
                  "$$value",
                  [
                    "$$this"
                  ]
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Mongo Playground

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda