如何更新集合中每个匹配的数组元素?

时间:2021-03-04 23:38:00

标签: javascript arrays mongodb

我的“Matches”集合具有以下结构,我需要遍历所有 290 条记录并将 playerName 值从“GYLNNALDINHO”更新为“GLYNNALDINHO”。该玩家出现在 290 条记录中的 77 条中。

{
    "_id" : ObjectId("6041690d9105df684c0c16c3"),
    "date" : ISODate("2021-03-04T23:10:27.000Z"),
    "game" : 290,
    "players" : [ 
        {
            "_id" : ObjectId("6041690d9105df684c0c16c6"),
            "playerName" : "GYLNNALDINHO",
            "playerGoals" : 0,
        {
            "_id" : ObjectId("6041690d9105df684c0c16c7"),
            "playerName" : "GLYNNALDO",
            "playerGoals" : 0,
        }
    ]
}

这是我正在运行的 robo3t 脚本:

db.getCollection('matches').find({})
    .forEach(match => {
        match.players.forEach(player => {
            if(player.playerName === "GYLNNALDINHO") {
                    player.playerName = "GLYNNALDINHO";
                    }
            })

        db.getCollection('matches').save(match);
});

我得到以下结果,但是当我再次检查表格时,它不会更新所有值。我不确定它是否真的更新了任何内容。上面的代码有问题吗?

Updated 1 existing record(s) in 48ms
Updated 1 existing record(s) in 48ms
Updated 0 record(s) in 48ms
Updated 1 existing record(s) in 48ms
Updated 0 record(s) in 50ms

1 个答案:

答案 0 :(得分:0)

代码没有任何问题,问题在于 Robo 3T 的外壳超时。它需要从 15 秒增加到 30 秒。