Arrays 更新MongoDB中嵌套数组中的值
我发现这个答案对我如何查询嵌套数组非常有帮助。我现在想要的是能够更新(推送或替换)嵌套数组中的值。例如,我想用“peach”替换所有“apple”值Arrays 更新MongoDB中嵌套数组中的值,arrays,mongodb,Arrays,Mongodb,我发现这个答案对我如何查询嵌套数组非常有帮助。我现在想要的是能够更新(推送或替换)嵌套数组中的值。例如,我想用“peach”替换所有“apple”值 我还发现了3个关于更新嵌套数组的问题,但它们的答案在本例中似乎没有帮助。那么我们如何修改内部数组中的值呢?我认为您要查找的是findAndyModify 基本上,您可以一次包含查询、删除项目和更新文档。例如,如果您想: 在键子文档中查找所有带有“apple”的文档 删除“apple”的所有实例 在数组末尾添加“peach” 它可能看起来像这样: d
我还发现了3个关于更新嵌套数组的问题,但它们的答案在本例中似乎没有帮助。那么我们如何修改内部数组中的值呢?我认为您要查找的是
findAndyModify
基本上,您可以一次包含查询、删除项目和更新文档。例如,如果您想:
键
子文档中查找所有带有“apple”的文档db.multiArr.findAndModify({
query: { Keys : 'apple' },
update: { $pull : { Keys : 'apple' }}, { $push : { Keys : 'peach' }},
new: true
});
编辑:
。它将生成以下错误消息:
findAndModifyFailed failed: {
"errmsg" : "exception: Field name duplication not allowed with modifiers",
"code" : 10150,
"ok" : 0
} at src/mongo/shell/collection.js:399
您只需在两次更新中完成:
// $push first or you won't be able to find the documents
db.multiArr.update({ Keys : 'apple' }, { $push : { Keys : 'peaches' }}, { multi : true });
db.multiArr.update({ Keys : 'apple' }, { $pull : { Keys : 'apple' }}, { multi : true });
为了补充前面的答案,如果您知道“apple”的索引,您可以硬编码如下:
db.multiArr.update({Keys:"apple"}, {$set: {"Keys.0":"peaches"}}, {multi:true})
db.multiArr.update({Keys:"apple"}, {$set: {"Keys.0":"peaches"}}, {multi:true})