mongodb - MongoDB查找包含具有连续匹配值的数组的所有对象
问题描述
我有一个 MongoDB 集合,如下所示:
{
_id: "some-long-id-1"
name: "John Doe",
activities: [
{ name: "Lunch", status: "SCHEDULED" },
{ name: "Playing Football", status: "COMPLETED" },
{ name: "Workout", status: "COMPLETED" },
]
},
{
_id: "some-long-id-2"
name: "Jane Doe",
activities: [
{ name: "Lunch", status: "COMPLETED" },
{ name: "Playing Football", status: "SCHEDULED" },
{ name: "Workout", status: "COMPLETED" },
]
}
我想查询所有activities
包含至少一个连续COMPLETED
状态的对象。例如,查询应该返回对象,因为它在活动数组中some-long-id-1
具有连续的状态。COMPLETED
它不应该返回some-long-id-2
,因为即使有两个具有COMPLETED
状态的数组但它们不是连续的。
解决方案
询问
- 将数组减少为一个数字(计算我们找到的连续数)
- 0 未找到
- 1 找到一个
- 2 找到 2
- 我们需要reduce结果为= 2
- if 2 => keep 2
else if "completed" => inc the number
else 0 (restart counts)
aggregate(
[{"$match":
{"$expr":
{"$eq":
[{"$reduce":
{"input": "$activities",
"initialValue": 0,
"in":
{"$switch":
{"branches":
[{"case": {"$eq": ["$$value", 2]}, "then": "$$value"},
{"case": {"$eq": ["$$this.status", "COMPLETED"]},
"then": {"$add": ["$$value", 1]}}],
"default": 0}}}}, 2]}}}])
推荐阅读
- swift - Thread1 -[Subject addTasksObject:]:无法识别的选择器发送到实例 0x60000293cb00'
- python - 将 Twilio 帐户添加到 whatsapp 组
- python - Python 提取两个时间戳之间的 JSON 对象模式
- javascript - 递增和递减 Firebase Ionic 5
- javascript - useState 如何遍历数组
- javascript - 变量何时相互分配的规则
- docker - 在多个 gitlab 运行器实例上创建相同的缓存
- javascript - React Hooks:加载时立即随机播放数组,然后单击
- flutter - 我想在 Flutter 中显示复杂的 JSON 数据但一无所获
- assembly - 什么是 gdb 中的“堆栈”部分