python - mongodb group and combine -


i have doc has schema {'year-month-day','others'} , want convert 'year-month-day isodate time can use $match:{'$gte:targetdate'}

i have several problems:

  1. i using pymongo, dones support javaciprt, can not use new date() in python , @ same time datetime not working because can not read '$year'.

i think 1 way achieve above goal first substrings of 'year-month-day' , after aggregation can use foreach(function(x){...}) create isodate each date , compare target doing means have scan through every docs in database dont think choice.

  1. if first not doable in pymongo, how can mongodb query? how can use project create column new data type?(like did in second project).

  2. is there way javascrip inside pymongo?

my script following:

collection.aggregate([                                     {                     '$project':{                         'year':{'$substr':['$year-month-day',0,4]},                         'month':{'$substr':['$year-month-day',5,2]},                         'day':{'$substr':['$year-month-day',8,2]},                         'others':'others'                      }                     },                 {                     '$project':{                         'approtime':new date(date.utc('$year','$month','$day')),                         'others':'others'                      }                     },                 {                     '$group':{                         '_id':{                             'approtime':'$approtime',                             'others':'others'                         },                         'count':{'$sum':1}                     }                 } 

you try converting field 'year-month-day' mongodb native isodate data type using datetime module stored under hood native date object in mongodb:

from pymongo import mongoclient datetime import datetime  client = mongoclient('host', port) db = client['database'] col = db['collection'] attr = 'year-month-day' date_format = "%y-%m-%d %h:%m:%s.%f" #date_format format of string eg : "%y-%m-%d %h:%m:%s.%f" doc in col.find():     if doc[attr]:         if type(doc[attr]) not datetime:             isodate = datetime.strptime(doc[attr], date_format)             col.update({'_id': doc['_id']}, {'$set': {attr: isodate}}) 

this can done in mongo shell as:

db.collection.find({     "$and": [         { "year-month-day": { "$exists": true } },         { "year-month-day": { "$not": {"$type": 9} } }     ] }).foreach(function(doc) {      doc["year-month-day"] = new date(doc["year-month-day"]);     db.collection.save(doc);  }) 

Comments

Popular posts from this blog

timeout - Handshake_timeout on RabbitMQ using python and pika from remote vm -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

c# - Search and Add Comment with OpenXML for Word -