我在django中使用mongoengine作为mongodb。
但是...... mongoengine字段(比如StringField)让我按照我不想要的方式构建架构。我的意思是,它严格坚持在我知道它之前预先写好关键名称。例如......
如果我不知道将什么密钥名称放入数据库...
> 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 }
[加成]
如上所示,关键是彼此非常不同的.. 只是假设“我不知道将哪个关键名称提前放入文档作为关键
正如dcrosta回复的那样..我正在寻找一种方法来使用mongoengine而不提前指定字段。
[/加成]
我如何通过mongoengine做同样的事情? 请给我一些类似
的架构设计class Test(Document):
tag = StringField(db_field='xxxx')
[加成]
我不知道'xxxx'将作为关键名称。
抱歉..我是韩国人,所以我的英语很尴尬。 请告诉我你的一些知识。 感谢您阅读本文。[/加成]
答案 0 :(得分:2)
您是否考虑过直接使用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。