pythonmongodbmongodb-queryaggregation-frameworkmotorengine

Python [mongo] - convert return fields of find()


need to get specific fields from Mongo, The DB is huge so I prefer getting the values in right format and not post processing it .

in example, There are 2 fields which need to convert the format:

1_id: ObjectId('604e0dbc96a0c93a45bfc5b0') to string as "604e0dbc96a0c93a45bfc5b0: 2.birthdate: ISODate('1999-11-10T00:00:00.000Z') - to string in date format "10/11/1999".

Example of json in MongoDB:

{
    _id: ObjectId('604e0dbc96a0c93a45bfc5b0'),
    address: 'BOB addrees',
    name: 'BOB',
    last_name: 'Habanero',
    birthdate: ISODate('1000-11-10T00:00:00.000Z')
}

retrieving the Jsons specific fields:

customers_cursor =  DB.customer.find({},{"_id": 1,"name" :1 ,"last_name":1 ,"customer_type":1,"address.0":1 ,"email":1 ,"birthdate" :1 ,"customer_status":1} )

Is there an option to use convert functions for returning values in find() ? case not , what are my best option to do it while i have several fields required to format the values and there are MILLION of records in the MongoDB?


Solution

  • Demo - https://mongoplayground.net/p/4OcF0O74PvU

    You've to use an aggregation query to do that.

    convert object to string using $toString

    Use $dateToString to format your date

    db.collection.aggregate([
      {
        "$project": {
          "_id": {
            "$toString": "$_id"
          },
          "name": 1,
          "last_name": 1,
          "customer_type": 1,
          "address.0": 1,
          "email": 1,
          "birthdate": {
            "$dateToString": {
              "format": "%d/%m/%Y",
              "date": "$birthdate"
            }
          },
          "customer_status": 1
        }
      }
    ])