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

121
Vistas
AddField an array of object using Aggregate

Supposedly I want to get a an object from my collection, an to this object, I want to add a property that will store an array of object containing ids and title matching one of the property of my object (in my case series).

Example I have this object as a result from my initial query

{
   _id: 13123123123,
   title: "TitleofObject",
   series: "SeriesName",
}

then I want to look on the same collection where the series name is the same for my object (add a new property named sameSeries to store objects matching the series) and the final result of object should look something like this

    _id: 13123123123,
   title: "TitleofObject",
   series: "SeriesName",
   sameSeries: 
    [
      {
      _id: 12312312,
      title: "anothertitleofObject"
      }, 
      {
      _id: 12312342312,
      title: "anothertitleofObject2"
      }
    ]
   

How can I achieve this using the aggregate method?


 const book = await Book.aggregate([
       {
            $match: { _id: id }
       },
])

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

db.collection.aggregate([
  {
    "$group": { //Group by series
      "_id": "$series",
      "sameSeries": { //Create an object
        $push: { //push the required fields
          "title": "$title",
          "_id": "$_id"
        }
      }
    }
  }
])

playground

db.collection.aggregate([
  {
    "$match": {
      "_id": 13123123123,
      "sameSeries": {
        "$exists": false
      }
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "localField": "series",
      "foreignField": "series",
      "as": "sameSeries"
    }
  }
])

Playground

To skip the parent id, you can do a slice

db.collection.aggregate([
  {
    "$match": {
      "_id": 13123123123,
      
    }
  },
  {
    "$lookup": {
      "from": "collection",
      "localField": "series",
      "foreignField": "series",
      "as": "sameSeries"
    }
  },
  {
    "$project": {
      _id: 1,
      series: 1,
      title: 1,
      sameSeries: {
        "$slice": [
          "$sameSeries",
          -1
        ]
      }
    }
  }
])

Play

about 4 years ago · Juan Pablo Isaza 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