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

73
Vistas
How to get the last N elements with a matching key from a MongoDB collection

I have a Collection of documents that looks like this:

[
 {
   "_id": "588cf61e5120ac11d4366f5c",
   "title": "This is a test entry",
   "entrybody": "This is the body of an entry",
   "creationdate": 1111,
   "author": "1223cllclclclc",
   "__v": 0
  },
 {
   "_id": "588cf6a556414f02f4e6a865",
   "title": "This is a new entry",
   "entrybody": "This is the body of an nuew entry",
   "creationdate": 11114040050505,
   "author": "1223cllclclclclslslsl",
   "__v": 0
 },
 {
   "_id": "588cf767fc2ede200cd5738e",
   "title": "This is a new entry",
   "entrybody": "This is the body of an nuew entry",
   "creationdate": 11114040050505,
   "author": "1223cllclclclclslslsl",
   "__v": 0
   }
  .....
]

I would like to get the last n records of each author and then order them by creation date, i have looked up how to do this with aggregation but im stuck.

I need the last N documents of the collection that match an especific key e.g author, and then i have to sort that result by "creation date". I think thats different from this question mongodb: how to get the last N records?

Thanks in advance.

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

0

You can try something like this.

$sort to process the records for each author on last creationdate.

$group and $project to pick last N records for each author.

$unwind and $sort to process records by creationdate.

db.collection.aggregate({
    $sort: {
        author: 1,
        creationdate: -1
    }
}, {
    $group: {
        _id: "$author",
        data: {
            $push: "$$ROOT"
        }
    }
}, {
    $project: {
        _id: 0,
        lastN: {
            $slice: ["$data", N]
        }
    }
}, {
    $unwind: "$lastN"
}, {
    $sort: {
        "lastN.creationdate": -1
    }
})
over 4 years ago · Santiago Trujillo Denunciar

0

Here is an alternative way to solve the problem with help of forEach method:

var result = {};
db.collection.find().sort({"author": 1, "creationda‌‌te":-1}).forEach(function(doc) { 
    if (!(doc.author in result)) { 
        result[doc.author] = [];
    }
    if (result[doc.author].length < 5) { 
        result[doc.author].push(doc); 
    } 
})

After execution, the result variable is filled with documents separated by author's name like

{
    'author1': [
        {doc1},
        {doc2}
    ],
    'author2': [
        {doc1},
        {doc2}
    ]
}
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