本文主要讲述在 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]}
} })
运行结果:
继续编辑,修改 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.$.$'
那么,我想更新数组中的数组下的一个元素这么办呢?下面介绍两种方法:1、遍历数组修改,2、使用 arrayfilter。个人推荐 arrayfilter 方式。
// 查找所有 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 } ] })
运行示意:
如对本文有疑问, 点击进行留言回复!!
MongoDB中数据的替换方法实现类Replace()函数功能详解
理解Redis持久化,RDB持久化和AOF持久化的不同处理方式
网友评论