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

92
Vistas
Query on Pymongo

I need to fetch two field from a record in a collection, say "cpyKey" and "devices". multiple records are there having same "cpyKey" and "devices". I need to extract the record with latest "run_date" field available in record, and sort the outcome in ascending order of "devices"

Using pymongo. Can anyone help me in framing the query

agg_result=list(db.xyz.aggregate(
    [#{
        #"$match":{}},
        {"$group":
            {"_id":"$cpyKey","Max Devices":{"$max":"$devices"}}}, #{"$sum":1} -->Gives no. of records related to "_id":"$cpyKey" field
        {"$sort":{"Max Devices":1}}
    ]))

previously I did this, but now , there needs to be a change .. instead of getting max of device, I need to have device from latest inserted record of particular cpyKey.

I tried :

mk=list(db.xyz.find({},{"_id":0,"run_date":1}).sort([('run_date',-1)]).limit(1))
print(mk)
#mk is extracting the latest run_date value, but it is associated with a cpyKey
agg_result=list(db.xyz.find({"run_date":mk[0]['run_date']},{"cpyKey":1,"devices":1,"_id":0}))
print(agg_result)
#while implimenting mk in above, it gives a record to which it is associated

But it does not give me values for all cpyKey

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

0

You can first sort by run_date

And then use $last in the group stage, to retrieve the corresponding Max Devices of the last element for each cpyKey

[
  {
    "$sort": {
      "run_date": 1
    }
  },
  {
    "$group": {
      "_id": "$cpyKey",
      "Max Devices": {
        "$last": "$Max Devices"
      }
    }
  },
  {
    "$sort": {
      "Max Devices": 1
    }
  }
]

try it here

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