pymongo: name 'ISODate' is not defined

前端 未结 2 1963
孤城傲影
孤城傲影 2020-12-21 18:37

I have problem when i try to select data in mongodb with pymongo, this is my code :

import pymongo
from pymongo import MongoClient
import sys
from datetime i         


        
2条回答
  •  离开以前
    2020-12-21 19:13

    ISODate is a JavaScript Date object. To query range of date using PyMongo, you need to use a datetime.datetime instance which mongod will convert to the appropriate BSON type. You don't need any third party library.

    Also you shouldn't be using the Aggregation Framework to do this because the _id field is unique within the collection which makes this a perfect job for the distinct() method.

    import datetime
    
    
    start = datetime.datetime(2016, 11, 11)
    end = datetime(2016, 11, 11, 23, 59, 59)
    
    db.session.distinct('_id', {'timestamp': {'$gte': start, '$lte': end}})
    

    If you really need to use the aggregate() method, your $match stage must look like this:

    {'$match': {'timestamp': {'$gte': start, '$lte': end}}}
    

提交回复
热议问题