Home > OS >  PyMongo gives error when using dot notation in field name for sort method
PyMongo gives error when using dot notation in field name for sort method

Time:10-01

I am trying to get the maximum value of a field inside a collection. The field's value is an array and I actually need to get the maximum of the first index of the array. For example, the collection is similar to this:

[
    {
        ...,
        "<field>": [10, 20],
        ...
    },
    {
        ...,
        "<field>": [13, 23],
        ...
    },
    {
        ...,
        "<field>": [19, 31],
        ...
    }
]

So from the above document, I would need to get the maximum of the first index of array. In this case, it would be 19.

To do this, I am first sorting the field by the first index of the field array and then getting the first document (using limit). I am able to do this using Node.js but cannot get it working with PyMongo.

It works using the Node.js MongoDB API like:

const max = (
    await collection
      .find()
      .sort({ "<field>.0": -1 })
      .limit(1)
      .toArray()
)[0];

However, if I try to do a similar thing using PyMongo:

max = list(collection.find().sort("<field>.0", -1).limit(1))[0]

I get the error:

KeyError: '<field>.0'

I am using PyMongo version 3.12.0. How can I resolve this?

CodePudding user response:

In PyMongo, the sort option is a list of tuples, where the tuples accept two arguments: key name and sort-order.

And you can pass multiple tuples to this list since MongoDB supports sort by multiple key conditions.

col.find({}).sort([('<key1>', <sort-order>), ('<key2>', <sort-order>)])

In your scenario, you should replace your find command as follows:

max = list(collection.find().sort([("<field>.0", -1)]).limit(1))[0]
  • Related