如何在MongoDB Shell中将游标结果插入集合?代码执行无效
I’ve run into this exact issue before—let’s break down why your script isn’t working and how to fix it, plus some better alternatives for larger datasets.
First, Diagnose the Root Cause
Your current code looks syntactically correct, but there are a few common pitfalls that might be causing it to silently fail:
Your
Patientscollection might be empty
Run this first to confirm you actually have data to migrate:print(`Total documents in Patients: ${db.Patients.countDocuments()}`); print(`Documents matching your query: ${db.Patients.find({}, {"patient_id":1}).countDocuments()}`);If either count is 0, that’s why
newCollectionstays empty.Cursor iteration edge cases
WhilehasNext()/next()works in theory, sometimes in certain MongoDB Shell versions, cursors can behave unexpectedly if not handled properly. Switching toforEach()is more reliable for cursor iteration.
Fixed Script with forEach()
Replace your while loop with this more robust version that includes validation steps:
// Verify source data exists first const sourceCount = db.Patients.find({}, {"patient_id":1}).countDocuments(); if (sourceCount === 0) { print("No documents found in Patients collection—exiting."); } else { print(`Migrating ${sourceCount} documents to newCollection...`); // Iterate and insert each document db.Patients.find({}, {"patient_id":1}).forEach(doc => { db.newCollection.insertOne(doc); }); // Verify the migration result const targetCount = db.newCollection.countDocuments(); print(`Migration complete! newCollection has ${targetCount} documents.`); }
Better: Use Aggregation for Large Datasets
If you’re dealing with more than a few hundred documents, looping with insertOne() is slow and inefficient. Use MongoDB’s aggregation framework for faster, atomic operations:
Option 1: Overwrite newCollection (fastest, atomic)
This replaces newCollection entirely with your query results—ideal for fresh migrations:
db.Patients.aggregate([ { $project: { patient_id: 1, _id: 0 } }, // Adjust projection to include/exclude fields as needed { $out: "newCollection" } ]);
Option 2: Merge with existing data
If newCollection already has data and you don’t want to overwrite it, use $merge to preserve existing documents:
db.Patients.aggregate([ { $project: { patient_id: 1, _id: 0 } }, { $merge: { into: "newCollection", whenMatched: "keepExisting", // Retain existing documents if there's a match whenNotMatched: "insert" // Insert new documents from the query } } ]);
Quick Checks to Rule Out Other Issues
- Confirm you’re in the right database: Run
db.getName()to make sure you’re working with the database that contains thePatientscollection. - Verify permissions: Even without errors, double-check that your user has
insertprivileges onnewCollection.
内容的提问来源于stack exchange,提问作者GregH

