MongoDB中具有动态键字段的JSON模式 [英] JSON Schema with dynamic key field in MongoDB
问题描述
想要对mongodb集合中存储的对象提供i18n支持
Want to have a i18n support for objects stored in mongodb collection
当前我们的模式如下:
{
_id: "id"
name: "name"
localization: [{
lan: "en-US",
name: "name_in_english"
}, {
lan: "zh-TW",
name: "name_in_traditional_chinese"
}]
}
但是我认为字段"lan"是唯一的,我可以只将该字段用作键,所以结构应该是
but my thought is that field "lan" is unique, can I just use this field as a key, so the structure would be
{
_id: "id"
name: "name"
localization: {
"en-US": "name_in_english",
"zh-TW": "name_in_traditional_chinese"
}
}
这将更加整洁且易于解析(仅localization [language]将获得我想要的特定语言的值).
which would be neater and easier to parse (just localization[language] would get the value i want for specific language).
但是接下来的问题是:这是在MongoDB中存储数据的好习惯吗?以及如何通过json模式检查?
But then the question is: Is this a good practice in storing data in MongoDB? And how to pass the json-schema check?
推荐答案
将值用作键不是一个好习惯.语言代码是值,正如您所说,您无法根据模式对其进行验证.这使得查询它成为不可能.例如,您无法确定您是否为"nl-NL"提供了语言翻译,因为您无法与键进行比较,也无法轻松地为其编制索引.您应该始终具有描述性的密钥.
It is not a good practice to have values as keys. The language codes are values and as you say you can not validate them against a schema. It makes querying against it impossible. For example, you can't figure out if you have a language translation for "nl-NL" as you can't compare against keys and neither is it possible to easily index this. You should always have descriptive keys.
但是,正如您所说的那样,将语言作为键可以更容易地提取数据,因为您可以通过['nl-NL']
(或任何语言的语法)进行访问.
However, as you say, having the languages as keys makes it a lot easier to pull the data out as you can just access it by ['nl-NL']
(or whatever your language's syntax is).
我建议使用其他模式:
{
your_id: "id_for_name"
lan: "en-US",
name: "name_in_english"
}
{
your_id: "id_for_name"
lan: "zh-TW",
name: "name_in_traditional_chinese"
}
现在您可以:
- 在
{ your_id: 1, lan: 1 }
上设置索引以快速查找 - 分别查询每个翻译,然后获取该翻译:
db.so.find( { your_id: "id_for_name", lan: 'en-US' } )
- 使用相同的索引查询每个id的所有版本:
db.so.find( { your_id: "id_for_name" } )
-
,并且更轻松地更新特定语言的翻译:
- set an index on
{ your_id: 1, lan: 1 }
for speedy lookups - query for each translation individually and just get that translation:
db.so.find( { your_id: "id_for_name", lan: 'en-US' } )
- query for all the versions for each id using this same index:
db.so.find( { your_id: "id_for_name" } )
and also much easier update the translation for a specific language:
db.so.update(
{ your_id: "id_for_name", lan: 'en-US' },
{ $set: { name: "ooga" } }
)
建议的模式中所有这些点都是不可能的.
Neither of those points are possible with your suggested schemas.
这篇关于MongoDB中具有动态键字段的JSON模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!