1. 程式人生 > >【Mongodb】使用Python對Mongodb中ObjectId的操作

【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可以比較大小。希望對有需求的人有幫助。