mongodb集团和联合

时间:2015-06-19 09:27:12

标签: python mongodb pymongo

我的文档的格式类似{'year-month-day','others'},我希望将'year-month-day转换为ISODate时间,以便我可以使用$match:{'$gte:targetDate'}

我有几个问题:

  1. 我正在使用pymongo,它支持javaciprt,所以我不能在python中使用new Date(),同时datetime也不能正常工作,因为它无法读取'$year'
  2. 我认为实现上述目标的一种方法是先获取'year-month-day'的子字符串,然后在聚合后我可以使用forEach(function(x){...})为每个日期创建ISODate并与{target进行比较1}}但这意味着我将不得不浏览数据库中的每个文档,我认为这不是一个好的选择。

    1. 如果第一个在pymongo中不可行,我怎么能通过mongodb查询呢?如何使用project创建具有新数据类型的列?(就像我在第二个项目中所做的那样)。

    2. 有没有办法在pymongo里面做javascrip?

    3. 我的脚本如下:

      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}
                          }
                      }
      

1 个答案:

答案 0 :(得分:0)

您可以尝试使用 datetime 模块将字段'year-month-day'转换为mongoDB本机ISODate数据类型,该模块作为MongoDB中的本机日期对象存储在引擎盖下:

from pymongo import MongoClient
from 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 is the format of the string eg : "%Y-%m-%d %H:%M:%S.%f"
for doc in col.find():
    if doc[attr]:
        if type(doc[attr]) is not datetime:
            isodate = datetime.strptime(doc[attr], date_format)
            col.update({'_id': doc['_id']}, {'$set': {attr: isodate}})

这也可以在Mongo shell中完成:

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); 
})