如何从Mongodb集合中具有大于零的时间(HH:MM:SS.Milisecond)值的日期字段中选择记录,并通过将日期值保持为零来将其更新为时间(HH:MM:SS)值为零存在于python脚本中.
目前的数据如下所示 –
1) "createdDate" : ISODate("2015-10-10T00:00:00Z")
2) "createdDate" : ISODate("2015-10-11T00:00:00Z")
3) "createdDate" : ISODate("2015-10-12T00:00:00Z")
4) "createdDate" : ISODate("2015-10-13T01:04:30.515Z")
5) "createdDate" : ISODate("2015-10-14T02:05:50.516Z")
6) "createdDate" : ISODate("2015-10-15T03:06:60.517Z")
7) "createdDate" : ISODate("2015-10-16T04:07:80.518Z")
如何使用mongodbsql仅选择行4,5,6,7并在python脚本中将时间戳更新为零 –
更新后的数据如下所示 –
1) "createdDate" : ISODate("2015-10-10T00:00:00Z")
2) "createdDate" : ISODate("2015-10-11T00:00:00Z")
3) "createdDate" : ISODate("2015-10-12T00:00:00Z")
4) "createdDate" : ISODate("2015-10-13T00:00:00Z")
5) "createdDate" : ISODate("2015-10-14T00:00:00Z")
6) "createdDate" : ISODate("2015-10-15T00:00:00Z")
7) "createdDate" : ISODate("2015-10-16T00:00:00Z")
解决方法:
更新文档和set
时间到00:00:00的最佳方法是使用datetime模块,因为createdDate是python中的datetime object,因此您可以使用datetime实例属性day
,year
和month
.
from datetime import datetime
from pymongo import MongoClient
client = MongoClient()
db = client.test
collection = db.collection
bulkOp = collection.initialize_ordered_bulk_op()
count = 0
for doc in collection.find():
year = doc['createdDate'].year
month = doc['createdDate'].month
day = doc['createdDate'].day
new_date = datetime(year, month, day)
bulkOp.find({'_id': doc['_id']}).update({'$set': {'createdDate': new_date}})
count = count + 1
if count == 125:
bulkOp.execute()
bulkOp = collection.initialize_ordered_bulk_op()
if count % 125 != 0:
bulkOp.execute()