pyMongo 一些基本操做

1. find() 函數, 能夠在函數體內直接指定 filter, sort, projection(限制field), 語法以下:html

datas = col.find(
  filter = {"$and":[{"_id":{"$gte":datetime.datetime(2017, 1, 20)}}, {"_id":{"$lte":datetime.datetime(2017, 1, 20, 7, 15, 30, 0)}}]},
  sort = [("_id", pymongo.ASCENDING)],
  projection = {"_id":1, "lastPrice":1})python

  也能夠寫成下面的樣子:mongodb

datas = col.find(
    {"$and":[{"_id":{"$gte":datetime.datetime(2017, 1, 20)}}, {"_id":{"$lte":datetime.datetime(2017, 1, 20, 7, 15, 30, 0)}}]},
    {"lastPrice":1, "_id":1}).sort("_id", pymongo.ASCENDING)

    

api: http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.findapi

 

2. pyMongo時間區間問題函數

  這裏: http://api.mongodb.com/python/current/examples/datetimes.htmlurl

  描述瞭如何自動轉化時區spa

  

>>> from bson.codec_options import CodecOptions
>>> db.times.find_one()['date']
datetime.datetime(2002, 10, 27, 14, 0)
>>> aware_times = db.times.with_options(codec_options=CodecOptions(
...     tz_aware=True,
...     tzinfo=pytz.timezone('US/Pacific')))
>>> result = aware_times.find_one()
datetime.datetime(2002, 10, 27, 6, 0,  
                  tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)

 

4. MongoClient 在url中直接指定dbcode

 db = pymongo.MongoClient("mongodb://127.0.0.1/MyDataBase").get_default_database()

get_default_database() 返回url中指定的dbhtm

相關文章
相關標籤/搜索