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

如何在单个JavaScript函数中执行多条MongoDB查询语句?

Combine MongoDB Review Migration into a Single Function

Here's a clean, reusable JavaScript function that executes your three operations in sequence—with error handling and feedback to make debugging easier:

function migrateProductReviews(productId) {
  try {
    // 1. Fetch all reviews for the target product
    const productReviews = db.reviews.find({ productID: productId }).toArray();
    
    if (productReviews.length === 0) {
      print(`No reviews found for product ID ${productId}. Nothing to do.`);
      return;
    }

    // 2. Update products collection by adding the reviews to the Reviews array
    const updateResult = db.products.update(
      { productID: productId },
      { $push: { Reviews: productReviews } },
      { multi: true }
    );

    print(`Updated ${updateResult.nModified} product document(s) with ${productReviews.length} reviews.`);

    // 3. Delete the original reviews from the reviews collection
    const deleteResult = db.reviews.remove({ productID: productId });
    print(`Deleted ${deleteResult.nRemoved} review document(s) for product ID ${productId}.`);

    return {
      success: true,
      reviewsFetched: productReviews.length,
      productsUpdated: updateResult.nModified,
      reviewsDeleted: deleteResult.nRemoved
    };
  } catch (error) {
    print(`Migration failed: ${error.message}`);
    return { success: false, error: error.message };
  }
}

// Run the function for product ID "123"
migrateProductReviews("123");

Key Details:

  • Reusability: The function accepts a productId parameter, so you can use it for any product, not just "123".
  • Error Handling: Wrapped in a try/catch block to catch and report any issues (e.g., missing collections, permission errors).
  • Early Exit: If no reviews exist for the product, the function stops early to avoid unnecessary database calls.
  • Feedback: Print statements show how many documents were processed at each step, which is helpful for verifying the operation worked as expected.

Important Note About $push:

Your original code uses $push: { Reviews: productReviews }, which adds the entire array of reviews as a single element in the product's Reviews array. If you want to append each review as an individual entry instead, modify the update step to use $each:

{ $push: { Reviews: { $each: productReviews } } }

This will add each review document separately to the Reviews array, which is probably what you want in most cases.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:33:13