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

132
Vistas
MongoDB get latest documents inside array object

My Schema looks something like this:

{
  id: {
    type: String,
    required: true,
    unique: true,
  },
  names: [
    {
      value: { type: String, required: true },
      changed_at: { type: Date, index: true, default: Date.now },
    },
  ],
}

With aggregation I want find 3 documents of my collection with the most recent date of names -> changed_at.

I tried something like this:

[
    { $unwind: '$names' },
    { $sort: { 'names.changed_at': -1 } },
    {
      $group: {
        _id: '$_id',
        names: { $push: { value: '$names.value', changed_at: '$names.changed_at' } },
        id: { $first: '$id' },
      },
    },
    { $limit: 3 },
    {
      $lookup: {
        from: 'users',
        localField: 'id',
        foreignField: 'id',
        as: 'user',
      },
    },
    { $unwind: '$user' },
    {
      $project: {
        _id: 0,
        old_name: { $first: '$names' },
        user: { avatar_url: 1, current_tag: 1 },
      },
    },
  ]

But this does not return the 3 most recent updated documents. How can I make up my query?

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

0

Query

  • create a multikey index on "names.changed_at"
  • sort on the array(names.changed_at) by -1, its like sorting based on the max member of the array

Test code here

db.collection.aggregate([
  {
    "$sort": {
      "names.changed_at": -1
    }
  },
  {
    "$limit": 3
  }
])

Query2 (alternative solution, like do manually what the above does auto)

  • for each document set the max-date, as extra field
    (its the document representative, shows the last date in all the names array)
  • sort by it
  • limit 3

=> you have the 3 documents that have the latests dates
(query doesn't return 3 latest global dates, those could be all in 1 document)

I used numbers for simplicity, dates are the same.

Test code here

db.collection.aggregate([
  {
    "$set": {
      "max-date": {
        "$max": "$names.changed_at"
      }
    }
  },
  {
    "$sort": {
      "max-date": -1
    }
  },
  {
    "$limit": 3
  }
])

If you can send some feedback on perfomance, if you have big collection. Comparing those 2 ways.

Second query can be super fast if you add to your schema, the field "max-date"(with index on it) and update it when you add dates on names (this will make very small index also, and will be fast for sure)

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