Reputation: 4897
MongoEngine is good for defining a document for data validation. Raw pymongo is lacking in this area. Can I use MongoEngine to define a document first, then use pymongo to insertMany documents into an empty collection? If yes, will pymongo's insertMany() do data validation based on the document definition set by mongoengine?
Can pymongo and mongoengine code be mixed together in the same python script?
I am using python 3.7, mongodb v4.2.7.
Upvotes: 1
Views: 590
Reputation: 1161
Your three questions:
'Can I use MongoEngine to define a document first, then use pymongo to insertMany documents into an empty collection? '
Yes.
'If yes, will pymongo's insertMany() do data validation based on the document definition set by mongoengine?'
No.
'Can pymongo and mongoengine code be mixed together in the same python script?'
Yes.
Mongoengine based on pymongo. If you do not need very complex function that mongoengine not had. I suggest you just use mongoengine to complete your work. This will save your time most of the time.
Upvotes: 1
Reputation: 2198
I'm a novice when it comes to Python and Mongo. I believe you can validate each document with MongoEngine like so:
for my_obj in my_objs:
my_obj.validate()
Then, bulk insert like so:
dicts = map(lambda my_obj: my_obj.to_mongo().to_dict(), my_objs)
collection.insert_many(dicts)
However, you can use MongoEngine to also bulk insert if you don't need to use PyMongo directly.
Upvotes: 0
Reputation: 203
Let me breakdown your question into three parts.
Answers -:
snap from mongoengine lib -- mongoengine -> common.py:
So, when you use validation in mongoenine these function is called and validate the data. If you want to validate you data for pymongo, then you have to write custom validation code for that.
Insertmany()
is seperate function, there is no relation with mongoengine. So mongoenine define is not worked with Insertmany()
.
Note -:
If you Use both pymongo and mongoenine together. Be careful, Because mongoengine have default validation function. So they check some validation before perform operations. But pymongo not have any validation, They just insert data and create collection [ If not exist ] and then insert data. So may be datatype conflict occur and problem like this.
Upvotes: 1