【问题标题】:How to update every matching array element in a collection?如何更新集合中每个匹配的数组元素?
【发布时间】:2021-03-04 23:38:00
【问题描述】:

我的“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

【问题讨论】:

标签: javascript arrays mongodb


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 2021-01-04
    • 1970-01-01
    • 2018-12-29
    • 2013-04-18
    • 1970-01-01
    相关资源
    最近更新 更多