问题
I want to use pymongo connection and methods to work with mongodb, but at the same time i want using mongoengine ORM.
Sample:
class User(Document):
email = StringField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)
john = User(email='jonhd@example.com')
john.first_name = 'Jonh'
john.last_name = 'Hope'
And now i want to insert new formed document User into my 'test_collection'. In case using only mongoengine i can do this:
connect('test_database')
john.save()
And then i can make easy accessing my data:
for user in User.objects:
print user.first_name
But when i'm trying to do same using pymongo, i've got an error:
connection = MongoClient('localhost', 27017)
db = connection.test_database
collection = db.test_collection
collection.insert(john)
Traceback:
Traceback (most recent call last):
File "C:/Users/haribo/PycharmProjects/test/mongoeng.py", line 18, in <module>
collection.insert(john)
File "C:\Python27\lib\site-packages\pymongo\collection.py", line 353, in insert
docs = [self.__database._fix_incoming(doc, self) for doc in docs]
File "C:\Python27\lib\site-packages\pymongo\database.py", line 258, in _fix_incoming
son = manipulator.transform_incoming(son, collection)
File "C:\Python27\lib\site-packages\pymongo\son_manipulator.py", line 73, in transform_incoming
son["_id"] = ObjectId()
TypeError: 'str' object does not support item assignment
But this works:
connection = MongoClient('localhost', 27017)
db = connection.test_database
collection = db.test_collection
john = { 'email': 'jonhd@example.com', 'first_name': 'Jonh', 'last_name': 'Hope' }
collections.insert(john)
And accessing data using pymongo:
print collection.find_one()
{u'last_name': u'Hope', u'first_name': u'Jonh', u'_id': ObjectId('513d93a3ee1dc61390373640'), u'email': u'jonhd@example.com'}
So, my main idea and question is:
How i can using mongoengine for ORM and pymongo connection and methods to working with mongodb?
P.S. I mentioned that i want use it in pyramid for some context.
回答1:
Pymongo takes python dictionaries (or dictionary like objects) and persists them to mongoDB. Pymongo cannot take MongoEngine class instances and persist them.
MongoEngine is an orm wrapper that uses pymongo underneath and has a method on the Class instance to save eg: john.save()
What happens inside the MongoEngine code is it converts the data from the john
instance into a dictionary that can be stored in MongoDB via pymongo.
来源:https://stackoverflow.com/questions/15334056/insert-data-by-pymongo-using-mongoengine-orm-in-pyramid