EN VI

Python - How to sort array in mongo document field?

2024-03-12 00:30:06
Python - How to sort array in mongo document field

I have mongo document and i am getting it with find_one

I actually dont need answer with python example. I can accept just a mongo query for that example

obj = await collection.find_one({'fields.uuid': obj_uuid})
{
    _id: ObjectId('65d5e666deda15bb37f308fe'),
    deleted: false,
    fields: {
        'uuid': 'some_uuid',
        'employees': [
          {
            "first_name": "Anna"
          },
          {
            "first_name": "Bob"
          }
        ]
    }
}

And i am wondering if there is the way to sort this array in field employees. For example Bob to be first or last in this array?

I know there mongo has an aggregation with replacing fields but this works only on list

Solution:

You can use $sortArray to sort fields.employees based on first_name using the aggregate method like so:

db.collection.aggregate([
  {
    $match: {
      "fields.uuid": "some_uuid"
    }
  },
  {
    $set: {
      "fields.employees": {
        $sortArray: {
          input: "$fields.employees",
          sortBy: {
            "first_name": 1
          }
        }
      }
    }
  }
])

See HERE for a working example.

The $match stage is synonymous with the query used in a regular find or findOne method. Using a 1 or -1 for the sort reverses the order.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login