using key as value in Mongoengine

半腔热情 提交于 2019-12-02 03:11:24

Have you considered using PyMongo directly instead of using Mongoengine? Mongoengine is designed to declare and validate a schema for your documents, and provides many tools and conveniences around that. If your documents are going to vary, I'm not sure Mongoengine is the right choice for you.

If, however, you have some fields in common across all documents, and then each document has some set of fields specific to itself, you can use Mongoengine's DictField. The downside of this is that the keys will not be "top-level", for instance:

class UserThings(Document):
    # you can look this document up by username
    username = StringField()

    # you can store whatever you want here
    things = DictField()

dcrosta_things = UserThings(username='dcrosta')
dcrosta_things.things['foo'] = 'bar'
dcrosta_things.things['bad'] = 'quack'
dcrosta_things.save()

Results in a MongoDB document like:

{ _id: ObjectId(...),
  _types: ["UserThings"],
  _cls: "UserThings",
  username: "dcrosta",
  things: {
    foo: "bar",
    baz: "quack"
  }
}

Edit: I should also note, there's work in progress on the development branch of Mongoengine for "dynamic" documents, where attributes on the Python document instances will be saved when the model is saved. See https://github.com/hmarr/mongoengine/pull/112 for details and history.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!