如何在单个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
productIdparameter, so you can use it for any product, not just "123". - Error Handling: Wrapped in a
try/catchblock 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
相关产品推荐
相关产品推荐

