Yii2 MongoDB聚合报错:如何解决‘管道项必须是文档’问题
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$groupstage, finish thecountfield 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 yourassignedOnfield stores MongoDBDateobjects (not plain strings), comparing with string dates won't work. Convert your date strings toMongoDB\BSON\Dateinstances 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

