I'm loading some dates into mongodb using pymongo. Because pymongo does automatic conversions to BSON, I'm working with datetime's datetime.strptime function to turn input strings like "12/04/2013" into Date objects like so:
>>> datetime.datetime.strptime("12/04/2013",'%m/%d/%Y')
datetime.datetime(2013, 12, 4, 0, 0)
So that they can be searchable using standard mongo queries.
My problem is: I would also like to represent that I do not know what date something is in a way equivalent to None
, so that I can do None
null-tests on it. I realize I could just put this date very far in the past or future with a try-catch block for entering ''
or None
, but this is hacky thinking and I'd rather use a proper None-type to represent what is actually a None.
How can I enter a None datetime?
DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.
format is the format – 'yyyy-mm-dd'
Use model. myDate. HasValue. It will return true if date is not null otherwise false.
When you search MongoDB null
and missing values are equivalent.
> db.foo.insert({a: null})
> db.foo.insert({})
db.foo.find({a: null}, {_id: 0})
{ "a" : null }
{ }
It works the same way with pymongo
:
>>> [doc for doc in pymongo.MongoClient().test.foo.find({'a': None}, {'_id': 0})]
[{u'a': None}, {}]
So None
seems to be a good choice. It is consistent with Python semantics, it plays nice with default behavior of dict.get
method and maps intuitively to MongoDB types when using Python driver.
MongoDB is a NoSQL database, meaning that you can make interesting data models.
http://docs.mongodb.org/manual/core/data-modeling-introduction/
Each document in your collection does not need to have the same set of field names. If you do not know the date, you may simply leave it out. Your application code can easily check the existence of of the timestamp when you want to retrieve the document
import pymongo
import datetime
mclient = pymongo.MongoClient()
mclient.test.example.insert({'Name': "Orange"})
mclient.test.example.insert({'Name': "Lemon", 'timestamp':datetime.datetime.now()})
for document in mclient.test.example.find():
if "timestamp" in document:
print document
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With