mongodb组和Combine

2024-05-16 23:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文档,它有一个类似{'year-month-day','others'}的模式,我想把'year-month-day转换成一个ISODate时间,这样我就可以使用$match:{'$gte:targetDate'}

我有几个问题:

  1. 我正在使用pymongo,它不支持javaciprt,所以我不能在python中使用new Date(),同时datetime也不能正常工作,因为它不能读取'$year'。你知道吗

我认为实现上述目标的一种方法是首先获得'year-month-day'的子字符串,在聚合之后,我可以使用forEach(function(x){...})为每个日期创建一个ISODate,并与target进行比较,但这样做意味着我必须扫描数据库中的每个文档,我认为这不是一个好的选择。你知道吗

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

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

我的剧本如下:

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

Tags: 文档projectnewdatematch时间模式year
1条回答
网友
1楼 · 发布于 2024-05-16 23:33:34

您可以尝试使用datetime模块将字段'year-month-day'转换为mongoDB native ISODate数据类型,该模块作为mongoDB中的native date对象存储在hood下:

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

相关问题 更多 >