簡體   English   中英

僅在滿足特定條件時才向 mongoDB 文檔數組添加新元素

[英]Add new element to mongoDB document array only if a certain condition is met

我有這個 mongoDB 文檔結構:

Game = {
  _id: 'randomObjectId',
  players: [Array of players ObjectIds],
  maxPlayers: 2,
  status: 'created' (or 'fully-booked')
}

當一個新玩家加入游戲時,我想將他添加到玩家數組中,並且只有在滿足此條件時才將游戲status更改為fully-bookedplayers.length < maxPlayers

回顧一下:

  • 如果players.length < maxPlayers ,檢查數據庫內部(使用查詢);
  • 如果是,更新文檔
  • 如果沒有發回錯誤響應(可選)

如果沒有此檢查,很容易使用以下方法進行查詢:

 Game.findByIdAndUpdate('randomObjectId', { $addToSet: { players: 'playerObjId' }, gameStatus: 'fully-booked' }, { new: true })

我不知道如何將此條件添加到此(或其他類型的)查詢中。 任何幫助表示贊賞。 謝謝

您可以嘗試如下聚合管道更新。 但是,如果已經訂滿,該命令將返回null 另請注意,如果您嘗試添加數組中已存在的玩家 ID,則不會添加。

db.collection.findOneAndUpdate(
    {
        _id: someObjectId,
        $expr: {
            $lt: [{ $size: "$players" }, "$maxPlayers"]
        }
    },
    [
        {
            $set: {
                players: { $setUnion: ["$players", [newPlayerObjectId]] }
            }
        },
        {
            $set: {
                status: {
                    $cond: {
                        if: { $lt: [{ $size: "$players" }, "$maxPlayers"] },
                        then: "created",
                        else: "fully-booked"
                    }
                }
            }
        }
    ],
    {
        returnNewDocument: true
    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM