sql >> Base de Datos >  >> NoSQL >> MongoDB

Obtenga los últimos documentos con un criterio distinto

Puede usar el marco de agregación para lograr esto:

 db.collection.aggregate(
          [
             {$match:
                  {action:'entry'}
             },
             {$group:
                  {_id:'$name',
                   first:
                         {$max:'$timestamp'}
                  }
             }
          ])

Si es probable que incluya otros campos en los resultados, puede usar $first operador

 db.collection.aggregate(
          [
             {$match:
                  {action:'entry'}
             },
             {$sort:
                  {name:1, timestamp:-1}
             },
             {$group:
                  {_id:'$name',
                   timestamp: {$first:'$timestamp'},
                   otherField: {$first:'$otherField'},
                  }
             }
          ])