Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write an empty dict field using mongoengine

I have observed mongo documents for which document[field] returns {}, but I can't seem to create such a document. Example:

import mongoengine

mongoengine.connect('FOO', host='localhost', port=27017)

class Foo(mongoengine.Document):
    some_dict = mongoengine.DictField()
    message = mongoengine.StringField()

ID = '59b97ec7c5d65e0c4740b886'
foo = Foo()
foo.some_dict = {}
foo.id = ID
foo.save()

But when I query the record, some_dict is not among the fields, so the last line throws an error:

import pymongo
CON = pymongo.MongoClient('localhost',27017)
x = CON.FOO.foo.find_one()
assert str(x['_id']) == ID
assert 'some_dict' in x.keys()
like image 519
zkurtz Avatar asked May 08 '26 07:05

zkurtz


1 Answers

One obvious workaround is to update the document after it's created, but it feels like too much of a hack. I would prefer if mongoengine made it easy to do directly:

import mongoengine
import pymongo
CON = pymongo.MongoClient('localhost',27017)
CON.Foo.foo.remove()

mongoengine.connect('FOO', host='localhost', port=27017)

class Foo(mongoengine.Document):
    some_dict = mongoengine.DictField()
    some_list = mongoengine.ListField()

ID = '59b97ec7c5d65e0c4740b886'
foo = Foo()
foo.id = ID
foo.save()

from bson.objectid import ObjectId
CON.FOO.foo.update_one({'_id': ObjectId(ID)},
                       {'$set': {'some_dict': {}}}, upsert=False)

x = CON.FOO.foo.find_one()
assert str(x['_id']) == ID
assert 'some_dict' in x.keys()
like image 167
zkurtz Avatar answered May 11 '26 02:05

zkurtz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!