我有一个这样的数据集:
{
name : 'Doc Name',
photos: [
{
name: 'photo1',
url: 'http://.....'
},
{
name: 'photo2',
url: 'http://......'
}
],
etc ...如何使用Monk https://github.com/LearnBoost/monk更新photo2?我可以使用索引,因为我现在正在迭代字段。
我在下面的尝试中出现了一个错误,并且我不能为JSON选择器使用变量(就像在索引中一样)。
collection.update({_id: data._id}, {photos[i].data: filename}, function(err, updatedata) {
});发布于 2014-02-03 10:06:16
可以使用位置$运算符更新数组中某个位置上的项
collection.update(
{ _id: data.id, "photos.name": "photo2" },
{ $set: { "photos.$.data": "yourdata" } }
)发布于 2014-02-03 10:11:55
所以我找到了我的问题的解决方案,但可能还有一些更好的选择,我不会回答这个问题。但对于其他有同样问题的人,我是这么做的:
我将MongoDB文档提取为Node.js中的对象,操作文档,然后在一条update语句中替换整个数组。例如,下面是一些伪代码:
collection.find({id: 1}, function(err, doc){
for(i=0; i< doc.array.length; i++) {
//do what you gotta do
doc.array[i].property = 'new value';
}
collection.update({id: 1}, {$set : {"doc.array": doc.array}}, function(err,doc){
console.log(err);
}
})https://stackoverflow.com/questions/21518416
复制相似问题