[Answered ]-Using key as value in Mongoengine

2👍

âś…

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.

👤dcrosta

Leave a comment