我在 django 中使用 mongoengine 作为 mongodb。
但是.. mongoengine 字段(如 StringField)使我以我不想要的方式构建模式。我的意思是,它严格要求我在知道 key 名称是什么之前就预先写好它。例如...
如果我不知道什么键名将被放入数据库......
> for(var i=0; i<10; i++){
... o = {};
... o[i.toString()] = i + 100;
... db.test.save(o)
... }
> db.test.find()
{ "_id" : ObjectId("4ed623aa45c8729573313811"), "0" : 100 }
{ "_id" : ObjectId("4ed623aa45c8729573313812"), "1" : 101 }
{ "_id" : ObjectId("4ed623aa45c8729573313813"), "2" : 102 }
{ "_id" : ObjectId("4ed623aa45c8729573313814"), "3" : 103 }
{ "_id" : ObjectId("4ed623aa45c8729573313815"), "4" : 104 }
{ "_id" : ObjectId("4ed623aa45c8729573313816"), "5" : 105 }
{ "_id" : ObjectId("4ed623aa45c8729573313817"), "6" : 106 }
{ "_id" : ObjectId("4ed623aa45c8729573313818"), "7" : 107 }
{ "_id" : ObjectId("4ed623aa45c8729573313819"), "8" : 108 }
{ "_id" : ObjectId("4ed623aa45c872957331381a"), "9" : 109 }
[添加]
正如您在上面看到的, key 彼此之间非常不同.. 只是假设“我不知道提前将什么键名称作为键放入文档中
正如 dcrosta 回答的那样。我正在寻找一种使用 mongoengine 的方法,而无需提前指定字段。
[/添加]
我如何通过 mongoengine 做同样的事情? 请给我架构设计,例如
class Test(Document):
tag = StringField(db_field='xxxx')
[添加]
我不知道“xxxx”将作为键名。
抱歉..我是韩国人,所以我的英语很尴尬。 请给我一些你的知识。 感谢您阅读本文。
[/添加]
最佳答案
您是否考虑过直接使用 PyMongo 而不是使用 Mongoengine? Mongoengine 旨在声明和验证文档的架构,并提供了许多与之相关的工具和便利。如果您的文档会有所不同,我不确定 Mongoengine 是否适合您。
但是,如果所有文档都有一些共同的字段,并且每个文档都有一些特定于其自身的字段集,则可以使用 Mongoengine 的 DictField
。这样做的缺点是键不会是“顶级”,例如:
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()
MongoDB 文档的结果如下:
{ _id: ObjectId(...),
_types: ["UserThings"],
_cls: "UserThings",
username: "dcrosta",
things: {
foo: "bar",
baz: "quack"
}
}
编辑:我还应该注意,Mongoengine 的“动态”文档开发分支正在进行中,其中 Python 文档实例上的属性将在保存模型时保存。请参阅https://github.com/hmarr/mongoengine/pull/112了解详细信息和历史记录。
关于python - 在 Mongoengine 中使用键作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8326361/