如何在Windows CMD的MongoDB中实现类似MSSQL的Talent字段更新?
Hey there! I get it—switching between SQL and MongoDB syntax can feel a bit jarring at first, but let's map your exact MSSQL update logic to MongoDB, especially since you're working in Windows CMD.
First, let's recap what your original MSSQL query does: it updates all rows in the Doctors table, replacing every space in the Talent field with &, then converting the entire string to lowercase.
MongoDB Equivalent (Using Aggregation Pipeline Updates)
MongoDB 4.2 and later supports using aggregation pipelines in update operations, which is perfect for this kind of string manipulation. Here's the equivalent command you'd run in the MongoDB Shell (or via CMD):
Step 1: Full Command (Mongo Shell/mongosh)
db.Doctors.updateMany( {}, // Matches ALL documents (no WHERE clause, just like your MSSQL query) [ { $set: { Talent: { $toLower: { $replaceAll: { input: "$Talent", find: " ", replacement: "&" } } } } } ] )
Step 2: Adapting for Windows CMD
If you're running this directly from Windows CMD (using mongosh or the older mongo command), you'll need to handle quote escaping properly. CMD treats double quotes specially, so you'll need to escape internal quotes with backslashes, and wrap the entire eval command in double quotes:
mongosh your_database_name --eval "db.Doctors.updateMany({}, [{ $set: { Talent: { $toLower: { $replaceAll: { input: \"$Talent\", find: \" \", replacement: \"&\" } } } } }])"
Key Notes to Keep in Mind
- Target Specific Documents: If you don't want to update every doctor, replace the empty
{}inupdateManywith a query filter (e.g.,{ Department: "Neurology" }to only update neurologists). - Test First: Before running the update, you can preview the transformed values to make sure they're correct with a
findquery:db.Doctors.find( {}, { Talent: 1, Preview_Transformed_Talent: { $toLower: { $replaceAll: { input: "$Talent", find: " ", replacement: "&" } } } } ).limit(5) // Shows first 5 docs with original and transformed values - Version Requirement: The aggregation pipeline update syntax requires MongoDB 4.2 or newer. If you're on an older version, you'll need to use a loop with
findOneAndUpdate, but upgrading is strongly recommended for better performance and functionality.
内容的提问来源于stack exchange,提问作者Totales

