python -【mongo】 处理Ob

2023-01-31 04:01:25 python

ObjectID简介

monGo存储的数据在没有特别指定_id数据类型时,默认类型为ObjectID

‘_id’: ObjectId(‘55717c9eb2c983c127000000’)

ObjectId is a 12-byte BSON type, constructed using:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 3-byte Machine identifier,
  • a 2-byte process id, and
  • a 3-byte counter, starting with a random value.

python处理方式

基本思路就是转换成时间对象 ,然后处理.

objectid – Tools for working with mongoDB ObjectIds
Tools for working with MongoDB ObjectIds.

class bson.objectid.ObjectId(oid=None)
Initialize a new ObjectId.
  • 从ObjectID生成时间对象
from bson.objectid import ObjectId
a = ObjectId('55717c9eb2c983c127000000')
a.generation_time.timetuple() 

In [29]: a.generation_time.timetuple()
Out[29]: time.struct_time(tm_year=2015, tm_mon=6, tm_mday=5, tm_hour=10, tm_min=40, tm_sec=30, tm_wday=4, tm_yday=156, tm_isdst=0) 

#到了这种格式就可以随便处理了
In [30]: time.strftime("%Y-%m-%d %H:%M:%S",a.generation_time.timetuple())
Out[30]: '2015-06-05 10:40:30'
  • 生成ObjectID
# 时间对象转换
>>> gen_time = datetime.datetime(2010, 1, 1)
>>> dummy_id = ObjectId.from_datetime(gen_time)

>>> ObjectId(b'foo-bar-quux')
ObjectId('666f6f2d6261722d71757578')
>>> ObjectId('0123456789ab0123456789ab')
ObjectId('0123456789ab0123456789ab')
>>>
>>> # A u-prefixed unicode literal:
>>> ObjectId(u'0123456789ab0123456789ab')
ObjectId('0123456789ab0123456789ab')

相关文章