Home > other >  pymongo sort dictionaries inside of an array by date
pymongo sort dictionaries inside of an array by date

Time:10-28

I want some of your knowledge in here.

What I'm trying to do, is to sort the dates (datetime) of the dictionaries (from the oldest to newest) which is inside of an array from my MongoDB database.

{"_id": {
"$oid": "63595cb35e81b89cb442087c",
"Carrots": [
{
  "task": "Plantation",
  "date": "2022-01-16T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "Cleaning",
  "date": "2022-01-25T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "Cleaning",
  "date": "2022-01-08T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "Grass-cutting",
  "date": "2022-01-28T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "Cleaning",
  "date": "2022-01-09T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "re-plantation",
  "date": "2022-01-10T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "Grass-cutting",
  "date": "2022-01-23T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "re-plantation",
  "date": "2022-01-01T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "re-plantation",
  "date": "2022-02-14T00:00:00",
  "info": "Yes it worked"
},
{
  "task": "re-plantation",
  "date": "2022-02-02T00:00:00",
  "info": "Yes it worked"
}]}

I have tried with f = mycol.find({'Carrots':{"$exists":True}}).sort("date", 1) but is not working for this example.

What I did and was returning me the correct format was the following:

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient['GARDEN']
mycol = mydb['garden_data']

f = mycol.find({'Carrots':{"$exists":True}})
for i in k:
        data = i['Carrots']
data.sort(key=lambda x: str(datetime.strptime(str(x["date"]),'%Y-%m-%dT%H:%M:%S')))
print(data)

I have a solution on my project, but I want to know how to make the same exact thing with pymongo.

I have also seen that some people are using mycol.aggregate but I couldn't find something understandable enough, so I can make it work.

Any help will be really appreciated.

Thanks in advance.

CodePudding user response:

One option is to use $sortArray:

pipeline = [
  {"$project": {
      "Carrots": {
        "$sortArray": {
          "input": "$Carrots",
          "sortBy": {"date": 1}
        }
      }
    }
  }
]
f = mycol.aggregate(pipeline)

See how it works on the playground example

  • Related