pymongo: name 'ISODate' is not defined

前端 未结 2 1954
孤城傲影
孤城傲影 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}}}
    
    0 讨论(0)
  • 2020-12-21 19:23

    ISODate is a function in the Mongo shell, which is a javascript environment, it's not available within Python.

    You can use dateutil for converting a string to datetime object in Python,

    import dateutil.parser
    dateStr = "2016-11-11T00:00:00.000Z"
    dateutil.parser.parse(dateStr)  # returns a datetime.datetime(2016, 11, 11, 00, 0, tzinfo=tzutc())
    

    Using PyMongo, if you want to insert datetime in MongoDB you can simply do the following:

    import pymongo
    import dateutil
    dateStr = '2016-11-11T00:00:00.000Z'
    myDatetime = dateutil.parser.parse(dateStr)
    client = pymongo.MongoClient()
    client.db.collection.insert({'date': myDatetime})
    
    0 讨论(0)
提交回复
热议问题