Using Python 3.4 I'm parsing a document read from MongoDB (3.0.2) - I perform various tests and generate JSON/BSON of the form below:
{
'FixedH': False,
'Mstereo': True,
'RecMet': False,
'Sstereo': True,
'bond': False,
'charge': False,
'isotope': False,
'length': 223,
'nocomponents': 1,
'nolayers': 6,
'stereo': True
}
If I try and write this back to MongoDB (from the shell) I get the following error:
ReferenceError: False is not defined at (shell):1:175
If I manually convert my booleans (False --> false) so that they are all lower case the error disappears and the document is written to the collection in MongoDB.
I'm guessing I'm not the first to encounter this problem but I can't find any published workarounds. How can I get around this case sensitivity mis-match?
The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False .
String in MongoDB must be UTF-8 valid. Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server. Boolean − This type is used to store a boolean (true/ false) value.
I know there are three ways of storing the boolean data in mongodb: 0 or 1 as a String. 0 or 1 as a Number. True or False as a Boolean.
If you are using MongoDB 4.2, you can use aggregation operators in your update statement, like: . findOneAndUpdate({_id: day.id},[{$set:{present:{$eq:[false,"$present"]}}}]); That will set present to true if it is false, and to false if it is any other value.
Are you inserting the documents from mongo shell? Mongo shell won't accept 'False' or 'True' as boolean values. You should use a Python Mongo driver client. Pymongo should work. Check the below sample:
import pymongo
client = pymongo.MongoClient('localhost', 27017)
db = client.testdatabase
col = db.testcollection
col.insert({'FixedH': False,'Mstereo': True,'RecMet': False,'Sstereo': True,'bond': False,
'charge': False, 'isotope': False,'length': 223,'nocomponents': 1,
'nolayers': 6,'stereo': True})
cursor = col.find()
print 'Found', cursor.count()
print cursor.next()
client.close()
Call json_str = json.dumps(YOUR_OBJECT)
and then insert it into MongoDB from shell
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