本文主要讲述在 mongodb 中,怎么更新嵌套数组的值。mongodb
db.collection.update( { <array>: value ... }, { <update operator>: { "<array>.$" : value } } )
for (let i = 0; i < 3; i++) { let data = { name1_1: 'test' + i, arr_1: [{ a: i, b: 2 }, { a: i + 1, b: 2 }] }; db.nestedUpdate.insert(data); }
数据截图:数据库
db.nestedUpdate.updateMany({ 'arr_1.a': 1 }, { $set: { 'arr_1.$.a': 11, 'arr_1.$.b': 12, } })
运行后数据截图:数组
db.nestedUpdate.updateMany({ 'arr_1.a': 11 }, { $set: {
'arr_1.$': {a:11, c:[1,2,3]}
} })
运行结果:ide
继续编辑,修改 arr_1.c 的元素,很容易想到以下:测试
db.nestedUpdate.updateMany({ 'arr_1.c': 1 }, { $set: { 'arr_1.$.$': 11, } })
然而,最终的运行结果倒是: [Error] index 0: 2 - Too many positional (i.e. '$') elements found in path 'arr_1.$.$' spa
那么,我想更新数组中的数组下的一个元素这么办呢?下面介绍两种方法:一、遍历数组修改,二、使用 arrayFilter。我的推荐 arrayFilter 方式。code
// 查找全部 var all1 = db.nestedUpdate.find({}); all1.forEach(function(it) { var modified = false; // 遍历 arr_1 for (var i = 0; i < it.arr_1.length; ++i) { var ac1 = it.arr_1[i]; // 判断须要修改的 if (ac1.c && ac1.c.length > 0 && ac1.c[0] == 1) { ac1.c[0] = 1111; modified = true; } } if (modified) { db.nestedUpdate.save(it); } })
db.collection.updateMany( { <query conditions> }, { <update operator>: { "<array>.$[<identifier>]" : value } }, { arrayFilters: [ { <identifier>: <condition> } ] } )
如上,创建一个示例,把 arr_1.c的值改回去对象
db.nestedUpdate.updateMany({}, { $set: { 'arr_1.$[idx0].c.$[idx1]': 1 } }, { arrayFilters: [ { // idx0 知足条件: 需存在 c 字段 'idx0.c': { $exists: true }, }, { 'idx0.a': 1, }, { // idx1: 知足 值为 111 'idx1': 1111 } ] }); > [Error] index 0: 9 - Found multiple array filters with the same top-level field name idx0 at line 1, column 1
db.nestedUpdate.updateMany({}, { $set: { 'arr_1.$[idx0].c.$[idx1]': 1 } }, { arrayFilters: [ { // idx0 知足条件: 需存在 c 字段 'idx0.c': { $exists: true }, 'idx0.a': 1, }, { // idx1: 知足 值为 111 'idx1': 1111 } ] }); // 或 db.nestedUpdate.updateMany({}, { $set: { 'arr_1.$[idx0].c.$[idx1]': 1 } }, { arrayFilters: [ { // idx0 知足条件: 需存在 c 字段 idx0: { c: { $exists: true }, a: 1 } }, { // idx1: 知足 值为 111 'idx1': 1111 } ] });
db.nestedUpdate1.updateMany({}, { $set: { 'arr_1.$[].arr_1_1.$[idx1].arr1_1_1.$[idx2]': null } }, { arrayFilters: [ { // idx1: 知足 name <= 1 'idx1.name': { $lte: 1 } }, ] }) > [Error] index 0: 2 - No array filter found for identifier 'idx2' in path 'arr_1.$[].arr_1_1.$[idx1].arr1_1_1.$[idx2]' at line 1, column 1 > 时间: 0.003s
db.nestedUpdate1.updateMany({}, { $set: { 'arr_1.$[].arr_1_1.$[idx1].arr1_1_1.$[idx2]': null } }, { arrayFilters: [ { // idx1: 知足 name <= 1 'idx1.name': { $lte: 1 } }, { idx2: 1 } ] })
运行示意:blog