You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB查询:找出同一秒同时存在A、B标签的秒数

解决同一秒同时出现标签A和B的秒数提取问题

嘿,我来帮你搞定这个需求!从你提供的JSON结构里提取同时包含标签A和B的秒数,其实只要梳理清楚数据层级,然后针对性遍历检查就行。

先理清数据结构

你的JSON里,目标数据藏在level1数组的第三个元素里,level2下的level3是一个二维数组——每一个子数组对应同一秒内的所有标签元素(比如第三个子数组就是秒2的A和B两个元素)。

实现思路

  1. 先定位到level3这个二维数组;
  2. 遍历每一个子数组(每一组对应同一秒的元素);
  3. 检查该组内是否同时存在label为"A"和"B"的元素;
  4. 收集符合条件的秒数,最终得到结果列表。

JavaScript 实现示例

const data = { "level1": [ {}, {}, { "level2": { "level3": [ [ { "second": 0 } ], [ { "second": 1, "label": "A", "frame": 40 } ], [ { "second": 2, "label": "A", "frame": 60 }, { "second": 2, "label": "B", "frame": 60 } ], [ { "second": 3, "label": "B", "frame": 90 } ] ] } } ] };

// 精准定位到存储秒级数据的二维数组
const level3 = data.level1[2].level2.level3;
const targetSeconds = [];

level3.forEach(secondGroup => {
    // 获取当前组的秒数(取组内第一个元素的second,确保同一组秒数一致)
    const currentSecond = secondGroup[0]?.second;
    if (currentSecond === undefined) return;

    // 检查组内是否同时包含A和B标签
    const hasLabelA = secondGroup.some(item => item.label === 'A');
    const hasLabelB = secondGroup.some(item => item.label === 'B');

    if (hasLabelA && hasLabelB) {
        targetSeconds.push(currentSecond);
    }
});

console.log(targetSeconds); // 输出: [2]

Python 实现示例

如果你用Python处理,代码逻辑类似:

data = { "level1": [ {}, {}, { "level2": { "level3": [ [ { "second": 0 } ], [ { "second": 1, "label": "A", "frame": 40 } ], [ { "second": 2, "label": "A", "frame": 60 }, { "second": 2, "label": "B", "frame": 60 } ], [ { "second": 3, "label": "B", "frame": 90 } ] ] } } ] }

# 定位到目标二维数组
level3 = data['level1'][2]['level2']['level3']
target_seconds = []

for second_group in level3:
    if not second_group:
        continue
    # 获取当前组的秒数
    current_second = second_group[0].get('second')
    if current_second is None:
        continue

    # 检查是否同时存在A和B标签
    has_a = any(item.get('label') == 'A' for item in second_group)
    has_b = any(item.get('label') == 'B' for item in second_group)

    if has_a and has_b:
        target_seconds.append(current_second)

print(target_seconds)  # 输出: [2]

可选的严谨性优化

如果你的业务场景中,同一组内可能出现秒数不一致的异常情况,可以在检查标签前,先验证组内所有元素的second值是否相同:

  • JavaScript 里可以加:const isSameSecond = secondGroup.every(item => item.second === currentSecond);
  • Python 里可以加:is_same_second = all(item.get('second') == current_second for item in second_group)

只有当isSameSecond为true时,再进行标签检查,这样能避免异常数据干扰结果。

内容的提问来源于stack exchange,提问作者alexmark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:53:43