user3848207
user3848207

Reputation: 4897

Can one use mongoengine to define a document first, then use pymongo to insert many documents?

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

Answers (3)

Xu Qiushi
Xu Qiushi

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

jcragun
jcragun

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

Shubham gupta
Shubham gupta

Reputation: 203

Let me breakdown your question into three parts.

  1. Can i use mongoengine validation with pymongo ?
  2. If used insertmany then how do validate ?
  3. Can pymongo and mongoengine code be mixed together in the same python script?

Answers -:

  1. No you cannot use mongoengine validation with pymongo. Because validation is define in mongoengine module like -:

snap from mongoengine lib -- mongoengine -> common.py:

enter image description here

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.

  1. Insertmany() is seperate function, there is no relation with mongoengine. So mongoenine define is not worked with Insertmany().
  2. Yes, You can write pymongo and mongoengine code together in same python script. [In some scenario we need to do that].

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

Related Questions