MongoDB 3.6聚合查询报错:需指定cursor选项的问题求助
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 repeateddomainkey todomains,emails, anduserNamesso all your pushed values are preserved instead of overwriting each other. - Added
cursoroption: 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

