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

如何在MongoDB Shell中将游标结果插入集合?代码执行无效

Fixing MongoDB Shell Script to Insert Cursor Results into Another Collection

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 Patients collection 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 newCollection stays empty.

  • Cursor iteration edge cases
    While hasNext()/next() works in theory, sometimes in certain MongoDB Shell versions, cursors can behave unexpectedly if not handled properly. Switching to forEach() 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 the Patients collection.
  • Verify permissions: Even without errors, double-check that your user has insert privileges on newCollection.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:23:02