Select based on timestamp and update timestamp with zero(根据时间戳选择并用零更新时间戳)
问题描述
如何从 MongoDB 集合中时间 (HH:MM:SS.Milisecond) 值大于零的日期字段中选择记录,并将时间 (HH:MM:SS) 值更新为零保持日期值与 Python 脚本中的现有值相同?
How do I select records from a date field which has a time (HH:MM:SS.Milisecond) value greater than zero from a MongoDB collection and update it with a time (HH:MM:SS) value as zero by keeping the date value the same as the existing value in a Python script?
当前数据如下所示 -
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 脚本中将时间戳更新为零?
How do I select only rows 4, 5, 6, and 7 using mongodbsql
and update it with the timestamp as zero in a Python script?
更新后,数据如下所示 -
After an update, the data would look like as below -
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
实例属性 day
, year
和 月
.
The best way to update your documents and set
the time to 00:00:00
is using the datetime module, because createdDate
is a datetime object in Python, so you can use the datetime
instance attributes day
, year
, and 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()
这篇关于根据时间戳选择并用零更新时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!