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

Yii2 MongoDB聚合报错:如何解决‘管道项必须是文档’问题

Fixing "each item in the pipeline must be a document" Error in Yii MongoDB Aggregate

Hey, let's sort out this aggregation error you're running into with Yii and MongoDB. That error message basically means one (or more) stages in your aggregation pipeline isn't a valid MongoDB document—usually because of incomplete syntax or a malformed structure.

Looking at your code snippet, the most obvious culprit is the truncated $group stage: you have 'count' => ['$s... which cuts off mid-aggregation operator (like $sum or $avg). That incomplete structure is definitely causing the pipeline to reject the stage as an invalid document.

Step-by-Step Fixes:

  • Complete all aggregation stage syntax
    Make sure every stage in your pipeline is fully written. For your $group stage, finish the count field with a valid aggregation operator. For example, if you're trying to count entries per user, use $sum: 1:

    $collection = Yii::$app->mongodb->getCollection('lc_executive_allocate');
    $asCursor = true;
    $result = $collection->aggregate([
        [
            '$match' => [
                'stage' => '2',
                'completed' => '1',
                'status' => '1',
                'assignedOn' => ['$gte' => '2018-03-01', '$lte' => '2018-03-29'],
            ],
        ],
        [
            '$group' => [
                '_id' => ['userId' => '$userId'],
                'count' => ['$sum' => 1] // 补全完整的聚合操作符
            ],
        ]
    ], $asCursor);
    
  • Validate date comparisons (if applicable)
    If your assignedOn field stores MongoDB Date objects (not plain strings), comparing with string dates won't work. Convert your date strings to MongoDB\BSON\Date instances instead:

    'assignedOn' => [
        '$gte' => new \MongoDB\BSON\Date(strtotime('2018-03-01') * 1000),
        '$lte' => new \MongoDB\BSON\Date(strtotime('2018-03-29') * 1000),
    ]
    
  • Double-check pipeline structure
    Ensure each stage in your pipeline array is a single associative array with exactly one aggregation operator as the key (like $match, $group). Even small issues like missing commas or unclosed brackets can trigger this "invalid document" error—so do a quick syntax scan of all stages.

Key Takeaway

This error almost always stems from an incomplete or malformed stage in your aggregation pipeline. Fixing the truncated $group stage (and any other syntax oversights) should resolve the problem right away.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:09:51