我有一个这样的集合结构:
albums: {
2oBkjqYFwf3vrgDj4: {
_id: "2oBkjqYFwf3vrgDj4",
titles: [
{
titleText: "i am an album"
},
{
titleText: "this is my other title"
}
]
}
}
我想做下面这样的事情来更新标题文本等于某物的位置,然后更改它:
db.albums.update({"_id": "2oBkjqYFwf3vrgDj4", "titles": {$elemMatch: {"titleText": "i am an album"}}},
{$set: {
"titles.titleText": "i am not an album"
}
)
我知道我可以做一个foreach,但这似乎浪费了很多资源,因为我计划在titles.titleText
上有一个索引。
是我错过了什么,还是没有一个简单的方法可以做到这一点?我正在使用Meteor,但如果有办法在MongoDB中做到这一点,我认为它不应该改变任何逻辑。
谢谢大家!
原来我的问题是一个链接的转发
这个问题可以在MongoDB中通过做来解决,
db.albums.update({
"_id": "2oBkjqYFwf3vrgDj4",
"titles.titleText": "i am an album"
},
{$set:
{"titles.$.titleText": "i am not an album"}
}
)
当上一个问题发布时,minimongo不支持位置运算符。到目前为止,出于安全原因,mongo选择器不能从客户端代码中使用。
上面的方法必须从服务器上的 Meteor.method() 调用。
使用流星集合 api,您可以使用update
. 文档在这里。先提供一个选择器,然后提供一个修饰符。 你也可以直接用mongo做同样的事情。 一般语法如下,但我自己没有运行它。 我不知道是否存在一种类似于您的代码的更奇特的方式,也许是 DRY'er,但应该完成工作。
Albums.update(
{_id: "2oBkjqYFwf3vrgDj4", "titles.titleText": "i am an album"},
{$set:{"titles.titleText": "i am not an album"}}
};
客户端不能很好地工作。一个很好的解决方法是(在派对中找到他)的例子。
step 1: get the array for your items.
var album = albums.findOne().services;
step 2: lets find the index we want using _indexOf and _pluck
var indexToUpdate = _.indexOf(_.pluck('insert your array', 'insert your column name'), 'insert the one you want to update');
var modifier = { $set: {} };
modifier.$set["services." + indexToUpdate + ".youfieldinarray"] = 'your new value'.
step 3: update your item object
albumns.update(Business.findOne()._id, modifier);
不确定我会在大型集合中执行此操作,但对于较小的客户端,它运行良好。