mongodb: ¿cómo obtener los últimos registros N?


No puedo encontrar en ninguna parte se ha documentado esto. Por defecto, la operación find () obtendrá los registros desde el principio. ¿Cómo puedo obtener los últimos registros N en mongodb?

Editar: también quiero que el resultado devuelto esté ordenado de menos reciente a más reciente, no al revés.

Author: Ripon Al Wasim, 2010-12-12

9 answers

Si entiendo tu pregunta, necesitas ordenar en orden ascendente.

Suponiendo que tenga algún campo de id o fecha llamado "x", lo haría ...

.sort ()


db.foo.find().sort({x:1});

El 1 ordenará ascendente (más antiguo a más reciente) y -1 ordenará descendente (más reciente a más antiguo.)

Si utiliza el campo auto created _id tiene una fecha incrustada en él ... así que puedes usar eso para ordenar ...

db.foo.find().sort({_id:1});

Que devolverá todos sus documentos ordenados de más antiguo a más reciente.

Orden natural


También puede usar un Orden Natural mencionado anteriormente ...

db.foo.find().sort({$natural:1});

De nuevo, usando 1 o -1 dependiendo del orden que desee.

Uso .límite ()


Por último, es una buena práctica agregar un límite al hacer este tipo de consulta abierta para que pueda hacer cualquiera de las dos ...

db.foo.find().sort({_id:1}).limit(50);

O

db.foo.find().sort({$natural:1}).limit(50);
 554
Author: Justin Jenkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-13 01:23:54

Los últimos N registros agregados, de menos recientes a más recientes, se pueden ver con esta consulta:

db.collection.find().skip(db.collection.count() - N)

Si los quieres en el orden inverso:

db.collection.find().sort({ $natural: -1 }).limit(N)

Si instala Mongo-Hacker también puede usar:

db.collection.find().reverse().limit(N)

Si te cansas de escribir estos comandos todo el tiempo, puedes crear funciones personalizadas en tu ~/.mongorc.js. Por ejemplo,

function last(N) {
    return db.collection.find().skip(db.collection.count() - N);
}

Luego, desde un shell mongo, simplemente escriba last(N)

 87
Author: Trasplazio Garzuglio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-19 03:40:10

Para obtener los últimos N registros puede ejecutar la siguiente consulta:

db.yourcollectionname.find({$query: {}, $orderby: {$natural : -1}}).limit(yournumber)

Si solo desea un último registro:

db.yourcollectionname.findOne({$query: {}, $orderby: {$natural : -1}})

Nota: En lugar de natural natural puede usar una de las columnas de su colección.

 11
Author: Ashwini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-18 16:57:12

Puede utilizar sort() , limit() ,skip() para obtener el último registro N, comience desde cualquier valor omitido

db.collections.find().sort(key:value).limit(int value).skip(some int value);
 5
Author: pkp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-18 09:35:38

No puede "omitir" en función del tamaño de la colección, porque no tendrá en cuenta las condiciones de consulta.

La solución correcta es ordenar desde el punto final deseado, limitar el tamaño del conjunto de resultados, luego ajustar el orden de los resultados si es necesario.

Aquí hay un ejemplo, basado en código del mundo real.

var query = collection.find( { conditions } ).sort({$natural : -1}).limit(N);

query.exec(function(err, results) {
    if (err) { 
    }
    else if (results.length == 0) {
    }
    else {
        results.reverse(); // put the results into the desired order
        results.forEach(function(result) {
            // do something with each result
        });
    }
});
 5
Author: Marty Hirsch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-13 18:21:07

Busque en Consulta: Ordenación y Orden Natural, http://www.mongodb.org/display/DOCS/Sorting+y + Natural + Orden así como sort () bajo los métodos del cursor http://www.mongodb.org/display/DOCS/Advanced + Consultas

 4
Author: Steve Wilhelm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-12 10:35:42

Es posible que desee utilizar las opciones find : http://docs.meteor.com/api/collections.html#Mongo-Collection-find

db.collection.find({}, {sort: {createdAt: -1}, skip:2, limit: 18}).fetch();
 2
Author: Lucbug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-05 22:38:28

@bin-chen,

Puede usar una agregación para las últimas n entradas de un subconjunto de documentos de una colección. Aquí hay un ejemplo simplificado sin agrupar (lo que estaría haciendo entre las etapas 4 y 5 en este caso).

Esto devuelve las últimas 20 entradas (basadas en un campo llamado "timestamp"), ordenadas ascendentemente. Luego proyecta cada documents _id, timestamp y whatever_field_you_want_to_show en los resultados.

var pipeline = [
        {
            "$match": { //stage 1: filter out a subset
                "first_field": "needs to have this value",
                "second_field": "needs to be this"
            }
        },
        {
            "$sort": { //stage 2: sort the remainder last-first
                "timestamp": -1
            }
        },
        {
            "$limit": 20 //stage 3: keep only 20 of the descending order subset
        },
        {
            "$sort": {
                "rt": 1 //stage 4: sort back to ascending order
            }
        },
        {
            "$project": { //stage 5: add any fields you want to show in your results
                "_id": 1,
                "timestamp" : 1,
                "whatever_field_you_want_to_show": 1
            }
        }
    ]

yourcollection.aggregate(pipeline, function resultCallBack(err, result) {
  // account for (err)
  // do something with (result)
}

Entonces, el resultado se vería algo como:

{ 
    "_id" : ObjectId("5ac5b878a1deg18asdafb060"),
    "timestamp" : "2018-04-05T05:47:37.045Z",
    "whatever_field_you_want_to_show" : -3.46000003814697
}
{ 
    "_id" : ObjectId("5ac5b878a1de1adsweafb05f"),
    "timestamp" : "2018-04-05T05:47:38.187Z",
    "whatever_field_you_want_to_show" : -4.13000011444092
}

Espero que esto ayude.

 1
Author: lauri108,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-05 06:48:34

La última función debe ser sort, no limit.

Ejemplo:

db.testcollection.find().limit(3).sort({timestamp:-1}); 
 -5
Author: Ramesh Kasi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-19 14:04:11