node.js - 根据 MongoDB 中此数组中的条件元素编号推送数组中的元素
问题描述
假设我有这个集合things
:
db={
"things": [
{
_id: 1,
users: [
{
userId: 1,
role: "creator"
},{
userId: 2,
role: "spectator"
},{
userId: 3,
role: "left"
}
],
nbMax:2
},
{
_id: 2,
users: [
{
userId: 2,
role: "creator"
},{
userId: 1,
role: "spectator"
},{
userId: 3,
role: "left"
}
],
nbMax:3
}
]
}
我想在具有以下条件users
的给定字段中推送一个新用户_id
:具有角色的用户数creator
必须spectator
低于该字段nbMax
在这个例子中:
推送一个新用户_id
: 1 不起作用,因为nbMax
= 2 并且已经有 1 个创建者和 1 个观众(left
不计算在内)
为 : 2 推送一个新用户是_id
有效的,因为nbMax
= 3 并且已经只有 1 个创建者和 1 个观众。
有没有办法使用 mongodb 执行该操作,或者我应该将此查询拆分为 nodejs 中的 2 个查询,例如:_ 检查用户大小和nbMax
_ 如果可以:推送一个新用户
我已经尝试使用查询,update
但到目前为止没有任何效果,我想知道我想做的是否是一个好的 mongodb 实践。aggregate
$size
编辑:我创建了一个给定 _id的aggregate
用户数:creator
spectator
db.things.aggregate([
{
"$match": {
_id: 1
}
},
{
"$unwind": "$users"
},
{
"$match": {
"users.role": {
$in: [
"creator",
"spectator"
]
}
}
},
{
"$group": {
"_id": 1,
"count": {
"$sum": 1
}
}
}
])
这是一个演示
解决方案
推荐阅读
- dart - 我如何在应用导航器中观察新的导航器?
- listview - 如何分别更改每个list_Tile的字幕
- javascript - 如何使用 React 单击文档中的任意位置时关闭侧面板?
- azure - Microsoft 密码重置 - 包含重置后重定向 URI 的传递参数
- javascript - 在 JQuery 日期选择器上禁用 MySQL 数据库中的日期
- python - Flask API - 列出所有添加的资源
- ios - 可以在没有开发人员帐户的情况下使用推送通知吗?
- javascript - Jquery 从 if 语句中获取“this”
- python - 如何在 tkinter 中创建带有图像的按钮滑块?
- android - 我的其他应用未检测到模拟位置