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

使用PyMongo执行MongoDB更新查询时遭遇语法错误求助

Fixing the PyMongo Update Syntax Error with $set

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})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:33:34