【Mongodb】使用Python对Mongodb中ObjectId的操作

将Mongodb中ObjectId转换成时间戳

直接贴代码

import pymongo
import time
import datetime
from bson.objectid import ObjectId


def getTimestamp():
  connection = pymongo.MongoClient('localhost')
  with connection:
    db = connection['Test']
    table = db['rooms']
    data = table.find().sort( [['_id', -1]] ).limit(1)
    objectid = data.next()['_id']
    timestamp = timestamp_from_objectid(objectid)
    print(timestamp) #1490666759.0
    date_time = objectid.generation_time  #ObjectId convert datetime
    print(date_time) #2017-03-28 10:05:59+00:00

def timestamp_from_objectid(objectid):
  ''' ObjectId convert timestamp '''
  result = 0
  try:
    result = time.mktime(objectid.generation_time.timetuple())#get timestamp
  except:
    pass
  return result

if __name__ == '__main__':
  getTimestamp()

根据Mongodb中ObjectId获取某一时间段的数据

直接贴代码

import pymongo
import time
import datetime
from bson.objectid import ObjectId


def object_id_from_datetime(from_datetime=None):
    ''' According to the time manually generated an ObjectId '''
    if not from_datetime:
        from_datetime = datetime.datetime.now()
    return ObjectId.from_datetime(generation_time=from_datetime)


def range_search(start_timestamp, end_timestamp):
  connection = pymongo.MongoClient('localhost')
  with connection:
    db = connection['Test']
    table = db['rooms']
    count = table.find({'_id':{'$lt' : end_timestamp, '$gte' : start_timestamp}}).count()
    print(count) #get all record 

if __name__ == '__main__':
  #start time
  start_time = datetime.datetime(2017, 3, 28, 0, 0, 0)
  start_timestamp = object_id_from_datetime(start_time)
  #end time
  end_time = datetime.datetime(2017, 3, 29, 0, 0, 0)
  end_timestamp = object_id_from_datetime(end_time)
  range_search(start_timestamp, end_timestamp)

记录下来加深下自己的理解及记忆,没有难度, 只是不知道Mongodb中的ObjectId可以比较大小。希望对有需求的人有帮助。

你可能感兴趣的:(Python)