您可以使用$reduce https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/迭代数组并$cond https://docs.mongodb.com/manual/reference/operator/aggregation/cond/应用你的逻辑(连续否定)
载体格式正确
{
previous: // previous value to compare for continuity
acc: // number of consecutive negatives in the current sequence
max: // length of the longest sequence
}
$let https://docs.mongodb.com/manual/reference/operator/aggregation/let/是记住当前累加器以在最大值计算中重用。它是可选的但很方便:
db.collection.aggregate([
{
"$set": {
"x": {
"$reduce": {
"input": "$x",
"initialValue": {
previous: 0,
acc: 0,
max: 0
},
"in": {
$let: {
vars: {
result: {
"$cond": {
"if": {
"$and": [
{
"$lt": [
"$$this",
0
]
},
{
"$lt": [
"$$value.previous",
0
]
}
]
},
"then": {
"$add": [
"$$value.acc",
1
]
},
"else": {
"$cond": {
"if": {
"$lt": [
"$$this",
0
]
},
"then": 1,
"else": 0
}
}
}
}
},
in: {
previous: "$$this",
acc: "$$result",
max: {
"$cond": {
"if": {
$gt: [
"$$value.max",
"$$result"
]
},
"then": "$$value.max",
"else": "$$result"
}
}
}
}
}
}
}
}
},
{
"$set": {
x: "$x.max"
}
}
])
试试mongoplayground.net https://mongoplayground.net/p/LP0e3ppgOtt.