[英]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-booked
: players.length < maxPlayers
。
To recap:回顾一下:
players.length < maxPlayers
;players.length < maxPlayers
,检查数据库内部(使用查询); 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.