我目前有以下数据集:
{
'component_id':1,
'_locales':[
{
'url': 'dutch',
'locale': 'nl_NL'
}
] (etc)
}
Run Code Online (Sandbox Code Playgroud)
如果我想用语言环境更新行,我会运行类似于:
db.components.update(
{'component_id': 1, '_locales.locale': 'nl_NL'},
{$set: {'_locales.$': {'url': 'new url','locale':'nl_NL'}},
true
);
Run Code Online (Sandbox Code Playgroud)
这很好,直到语言环境不存在:
db.components.update(
{'component_id': 1, '_locales.locale': 'en_US'},
{$set: {'_locales.$': {'url': 'new url','locale':'en_US'}},
true
);
Run Code Online (Sandbox Code Playgroud)
因为component_id上有一个唯一索引,所以会抛出一个抱怨重复键的异常.
有没有办法自动添加具有不同语言环境的新"文档"并更新它(如果它已经存在)?根据使用位置运算符的文档将无法使用'upserting'.
考虑到写入速度,我应该将对象存储在数组中还是存储在最重要的对象中?
我正在尝试决定是将数据存储为对象数组,还是在 mongodb 文档中使用嵌套对象。
在这种特殊情况下,我会跟踪我添加和更新的一组不断更新的文件,文件名充当键以及文件中处理的行数。
该文件看起来像这样
{
t_id:1220,
some-other-info: {}, // there's other info here not updated frequently
files: {
log1-txt: {filename:"log1.txt",numlines:233,filesize:19928},
log2-txt: {filename:"log2.txt",numlines:2,filesize:843}
}
}
Run Code Online (Sandbox Code Playgroud)
或这个
{
t_id:1220,
some-other-info: {},
files:[
{filename:"log1.txt",numlines:233,filesize:19928},
{filename:"log2.txt",numlines:2,filesize:843}
]
}
Run Code Online (Sandbox Code Playgroud)
我假设处理一个文档,尤其是涉及到更新的时候,处理对象更容易,因为对象的位置可以通过名称来确定;与数组不同,在数组中我必须查看每个对象的值,直到找到匹配项。
因为对象键会有句点,我需要转换(或删除)句点以创建有效的键(fi.le.logtofilelog或fi-le-log)。我不担心文件可能出现的重复名称(例如fi.le.log和fi-le.log),所以我更喜欢使用对象,因为文件数量相对较少,但更新频繁。
或者最好在单独的集合中处理这些数据以获得最佳写入性能......
{
"_id": ObjectId('56d9f1202d777d9806000003'),"t_id": "1220","filename": "log1.txt","filesize": 1843,"numlines": 554
},
{
"_id": ObjectId('56d9f1392d777d9806000004'),"t_id": "1220","filename": "log2.txt","filesize": 5231,"numlines": 3027
}
Run Code Online (Sandbox Code Playgroud) 我正在使用Mean堆栈.我对此感到不舒服,并且让自己陷入困境.我已经看到使用set或push更新记录的例子,但因为我正在尝试更新json对象中json对象中的一个json对象,我遇到了麻烦.
请考虑以下Schema
token: {
type: String,
required: "FB access token required."
},
fbId: {
type: String,
required: "FB id required.",
unique: true
},
accounts: {
type: Array,
default: []
}
Run Code Online (Sandbox Code Playgroud)
我的帐户数组由json对象组成,每个对象看起来像这样:
{
"name": "some name",
"credentials": {
"username": "some username",
"password": "some password"
}
Run Code Online (Sandbox Code Playgroud)
每次用户添加新帐户时,我都会尝试更新帐户.所以在这种情况下我可以使用$ push就好了.但是我不想要重复的名字,$ push在这里失败了.所以我尝试使用$ set,但是$ set没有将具有新名称的对象插入到帐户中.所以我尝试使用upsert:true with $ set,但现在我收到了重复的错误.
这是我尝试在帐户中索引名称的示例.我假设我搞砸了我的查询.
var name = "some name";
var fbId = "some fb Id";
var token = "some token";
var username = "some other username";
var password = "some other …Run Code Online (Sandbox Code Playgroud)