【问题标题】:MongoDB upsert an array of objects from a listMongoDB从列表中插入一组对象
【发布时间】:2021-03-20 20:12:34
【问题描述】:

我正在将我的数据库从 sqlite3 移动到 mongo。我去了 通过 mongo 大学,但我不确定我是否找到了一个非常好的 批量更新插入的示例。

用例:用户上传包含玩家列表及其统计数据的数据文件。应用需要更新播放器或添加新播放器(如果它们尚不存在)。

当前实现:函数获取玩家列表并创建 SQL 语句。

let template = '(Player.Rank, Player.Player_ID, Player.Player, Player.Score, TTP, 1),(Player.Rank, Player_ID, ...) ... (... TTP, 1)';

const stmt = `INSERT INTO playerStats (Rank, Player_ID, Player, Score, TPP, Games_Played) 
VALUES ${template}
ON CONFLICT(Player_ID) DO UPDATE 
SET Score = Score+excluded.Score, TPP=TPP+excluded.TPP, Games_Played=Games_Played+1`;

db.run(stmt, callback);

我希望每个文档都是一个包含球员、比赛和经理的联盟。 Mongo DB 文档模板

{
    "LEAGUE_ID": "GEO_SAM",
      "Players": [
        {
          "id": "PlayerID",
          "name": "Player",
          "score": "Score",
          "rank": "Rank",
          "xPlayed": "Games_Played",
          "ttp": "TTP"
        }
      ],
      "Managers": [
        {...}
      ],
      "Games": [
        {...}
      ]
  }

我完全迷失了,不知道如何完成这项工作。我是否需要创建一个循环并要求 mongo 在每次迭代时进行 upsert?我搜索了无数示例,但所有示例都使用静态硬编码值。

这是我的测试示例。

const query = { League_id : "GEO_SAM", Players.$.id: $in{ $Players }};
const update = { $inc: { score: $Player.Score}};
const options = { upsert: true };
collection.updateMany(query, update, options);

如果没有找到 player_id,我也不明白如何传递整个播放器对象以推送到数组。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    我的解决方案是创建一个元数据字段,其中包含单个球员的联赛 ID。如果其他人有更好的解决方案,我很乐意听取您的意见。

       {
          MetaData: { "LEAGUE_ID": "GEO_SAM"},
          Player: {
            "id": "PlayerID",
            "name": "Player",
            "score": "Score",
            "rank": "Rank",
            "xPlayed": "Games_Played",
            "ttp": "TTP"
            }
      }
    

    然后我映射了这些值并插入了每个值。

    client.connect().then((client) => {
            const db = client.db(dbName);
            const results = Players.map((player) => {
              db.collection('Players').updateOne(
                { Player_Name: player.Player_ID },
                {
                  $setOnInsert: {
                    Player_ID: player.Player_ID,
                    Player: player.Player,
                    Rank: player.Rank,
                  },
                  $inc: { Score: player.Score, Games_Played: 1, TPP: player.TPP },
                },
                { upsert: true, multi: true },
              );
            });
    

    【讨论】:

      猜你喜欢
      • 2014-07-18
      • 2016-08-21
      • 2018-06-06
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2019-01-17
      • 1970-01-01
      相关资源
      最近更新 更多