简体   繁体   English

仅在满足特定条件时才向 mongoDB 文档数组添加新元素

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

I have this mongoDB document structure:我有这个 mongoDB 文档结构:

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

When a new player joins the game I want to add him to the players array and change the status of the game to fully-booked only if this condition is met: players.length < maxPlayers .当一个新玩家加入游戏时,我想将他添加到玩家数组中,并且只有在满足此条件时才将游戏status更改为fully-bookedplayers.length < maxPlayers

To recap:回顾一下:

  • Check inside the DB(using the query) if players.length < maxPlayers ;如果players.length < maxPlayers ,检查数据库内部(使用查询);
  • If yes update the document如果是,更新文档
  • If no send back an error response (optional)如果没有发回错误响应(可选)

Without this check it's easy to make the query using:如果没有此检查,很容易使用以下方法进行查询:

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

What I don't know is how to add this condition to this (or other type of) query.我不知道如何将此条件添加到此(或其他类型的)查询中。 Any help is appreciated.任何帮助表示赞赏。 Thanks谢谢

you can try an aggregation pipeline update like the following.您可以尝试如下聚合管道更新。 however, if already fully booked, the command will return a null .但是,如果已经订满,该命令将返回null also note that if you try to add a player id that already exists in the array, it won't be added.另请注意,如果您尝试添加数组中已存在的玩家 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.

相关问题 JavaScript - 仅当满足特定条件时,您能否将 class 添加到输入元素? - JavaScript - Can you add a class to an Input element only if a certain condition is met? 仅在满足特定条件时才执行调整大小功能 - Execute resize function only if a certain condition is met Rails:仅在满足特定条件时才包括JS - Rails: including JS only if a certain condition is met 仅在满足条件的情况下如何更新文档? - How to update a document only if a condition is met? 如果满足某个条件,则仅使用$ in运算符 - Mongoose - Only use $in operator if a certain condition is met - Mongoose 仅当满足某些条件时,JQuery才会自动完成 - JQuery autocomplete only if certain condition is met 仅在满足条件的情况下如何将元素添加到数组 - How to add an element to an array only if a condition is fulfilled 如果满足条件,则使用JQuery添加元素的链接 - Using JQuery to add a link to an element if a condition is met 如果满足特定条件,则生成新数组(Javascript) - Generating a new array if a certain criteria is met (Javascript) Javascript 满足条件时更新数组,否则将新记录添加到数组中 - Javascript update array when condition is met otherwise add new record to the array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM