Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass Boolean values created in Python to MongoDB?

Tags:

python

mongodb

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?

like image 458
ChemLynx Avatar asked May 17 '15 11:05

ChemLynx


People also ask

How do you pass a boolean value in Python?

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 .

Does MongoDB support boolean?

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.

How is boolean stored in MongoDB?

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.

How do I toggle boolean values in MongoDB?

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.


2 Answers

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()
like image 93
Nipun Talukdar Avatar answered Sep 19 '22 16:09

Nipun Talukdar


Call json_str = json.dumps(YOUR_OBJECT) and then insert it into MongoDB from shell

like image 44
Valijon Avatar answered Sep 20 '22 16:09

Valijon