1. find() 函数, 可以在函数体内直接指定 filter, sort, projection(限制field), 语法如下:
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})
也可以写成下面的样子:
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.find
2. pyMongo时间区间问题
这里: http://api.mongodb.com/python/current/examples/datetimes.html
描述了如何自动转化时区
>>> 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='US/Pacific' PST-1 day, 16:00:00 STD>)
4. MongoClient 在url中直接指定db
db = pymongo.MongoClient("mongodb://127.0.0.1/MyDataBase").get_default_database()
get_default_database() 返回url中指定的db