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

MongoDB 3.6聚合查询报错:需指定cursor选项的问题求助

Fixing the "cursor option is required" Aggregation Error in MongoDB 3.6

Hey there! Let's work through this issue step by step. First, let's break down why you're seeing that error and then fix your code properly.

Why the Error Happens

Starting with MongoDB 3.6, the aggregate() method requires the cursor option unless you're using the explain argument. Your current call doesn't include this option, which triggers the MongoError you're seeing.

On top of that, there's a bug in your $group stage: you're using the same domain key three times. Each subsequent $push will overwrite the previous one, so you'd only end up with the userName values in the end—you need unique keys for each field you're collecting.

Corrected Code

Here's the fixed version of your code that addresses both issues:

const user = await User.aggregate(
  [
    { 
      $group: { 
        _id: '$_id',
        domains: { $push: "$domain" },
        emails: { $push: "$email" },
        userNames: { $push: "$userName" }
      } 
    }
  ],
  { cursor: {} } // Required cursor option for MongoDB 3.6+
);

Key Changes Explained

  • Unique field names in $group: Renamed the repeated domain key to domains, emails, and userNames so all your pushed values are preserved instead of overwriting each other.
  • Added cursor option: The { cursor: {} } argument uses MongoDB's default cursor settings, which satisfies the 3.6+ requirement.

Optional: Get Results Directly as an Array

If you prefer to work with a plain array instead of a cursor, you can chain toArray() to the cursor object:

const aggregationCursor = User.aggregate(
  [
    { 
      $group: { 
        _id: '$_id',
        domains: { $push: "$domain" },
        emails: { $push: "$email" },
        userNames: { $push: "$userName" }
      } 
    }
  ],
  { cursor: {} }
);
const user = await aggregationCursor.toArray();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:42:17