使用PyMongo执行MongoDB更新查询时遭遇语法错误求助
Hey there! Let's break down why your update query is throwing a syntax error in Python but works fine in the Mongo Shell.
The Root Cause
Mongo Shell uses JavaScript syntax, which allows keys like $set without wrapping them in quotes. But Python is pickier—any dictionary key that starts with a special character (like $) needs to be enclosed in quotation marks to be valid syntax. Your problematic line is missing quotes around $set, which is why Python is screaming about invalid syntax.
The Fix
Wrap $set in double (or single) quotes to make it a valid Python dictionary key. Here's the corrected code:
db.fearlessData.update({"Country":"Canada"}, {"$set": {"Type":"Canadian_Wedding_2"}}, {"multi": True})
A Better Practice (Optional but Recommended)
PyMongo actually recommends using update_many() instead of relying on the multi parameter with update(), since it's more explicit and aligns with modern PyMongo best practices. Here's how that would look:
db.fearlessData.update_many({"Country":"Canada"}, {"$set": {"Type":"Canadian_Wedding_2"}})
This does the exact same thing as your original Shell command (updates all matching documents) but is cleaner and less error-prone.
Why Your Other Queries Worked
Your plain update query db.fearlessData.update({"Name":"Test_Elena2"},{"Name":"Test_Elena_3"}) worked because all the keys ("Name") are regular strings that don't require special handling in Python. The issue only pops up when you use MongoDB operators like $set, $inc, etc., which start with $.
Give the corrected code a try—it should run without syntax errors and behave just like your Mongo Shell command did!
内容的提问来源于stack exchange,提问作者Ketan

