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

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:

  1. $unwind turns your array into a single object
    After running $unwind: "$replacement_articles", the replacement_articles field is no longer an array—it's a single document from the originally joined array. When you try to use $size on it, MongoDB throws an error because $size requires an array, not a single object (or missing value if there were no matches).
  2. 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 $project with $size (if you skip $unwind) or a $group with $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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:37:16