Mongoose中$lookup结合$unwind使用$size统计报错求助
Hey there, let's figure out why you're hitting that MongoError and fix your aggregation query properly.
What's Causing the Error?
Your mistake comes from two key issues with your aggregation stages:
$unwindturns your array into a single object
After running$unwind: "$replacement_articles", thereplacement_articlesfield is no longer an array—it's a single document from the originally joined array. When you try to use$sizeon it, MongoDB throws an error because$sizerequires an array, not a single object (or missing value if there were no matches).- Incorrect stage and operator for counting
Your final stage is structured like a projection but uses$push, which is for collecting values into an array—not counting. To tally the number of related articles, you need either a$projectwith$size(if you skip$unwind) or a$groupwith$sum.
Fix 1: Skip $unwind (Most Efficient)
Since $lookup already returns an array of related replacement_articles, you can directly use $size to get the count without splitting the array. This is way more efficient because it avoids creating extra documents with $unwind.
aggregate([ { $lookup: { from: "replacement_articles", localField: "_id", foreignField: "userid", as: "replacement_articles" } }, { $project: { _id: "$_id", // Keep the original document ID article_count: { $size: "$replacement_articles" } // Get length of the joined array } } ])
Fix 2: Use $unwind + $group (If You Need Per-Article Processing)
If you must use $unwind (e.g., to run additional operations on individual replacement articles), you'll need to group back by the original document ID and count with $sum: 1. Also, add preserveNullAndEmptyArrays: true to keep users who have no related articles (otherwise they'll be filtered out).
aggregate([ { $lookup: { from: "replacement_articles", localField: "_id", foreignField: "userid", as: "replacement_articles" } }, { $unwind: { path: "$replacement_articles", preserveNullAndEmptyArrays: true // Retain users with no related articles } }, { $group: { _id: "$_id", // Group by the original user document's ID article_count: { $sum: 1 } // Count how many documents are in each group } } ])
内容的提问来源于stack exchange,提问作者Naresh P

