ImportError: cannot import name 'ObjectId' from 'bson'
Fixes the standalone bson PyPI package shadowing pymongo's bundled bson. Use when from bson import ObjectId fails. Not for missing pymongo installs.
TL;DR: You installed the standalone bson package from PyPI, and it shadows the bson that ships inside pymongo. Uninstall it: pip uninstall bson. Keep only pymongo, which bundles its own bson.
ImportError: cannot import name 'ObjectId' from 'bson'Fix it
- Confirm the culprit: pip show bson. Expected: a standalone bson package unrelated to pymongo.
- Remove it: pip uninstall bson -y. Expected: gone.
- Make sure pymongo is present: pip install pymongo. Expected: installed.
- Verify: python -c "from bson import ObjectId; print(ObjectId())". Expected: a fresh ObjectId, no traceback.
When this applies
- from bson import ObjectId fails and pip shows a standalone bson package.
When it doesn't
- pip shows no bson at all and pymongo is missing: pip install pymongo.
- The error is about another name: same shadowing pattern may apply to other dup packages.
Compatibility
- pymongo 3.x/4.x bundles bson; never install the standalone bson alongside.
Why it happens
Both packages install a top-level bson module. The standalone one wins the import race on some path orders, and it lacks ObjectId and the rest of pymongo's API.
Edge cases
- requirements files sometimes list bson explicitly from old copy-paste; delete the line.
- If some other dependency requires standalone bson, that dependency is broken by design; find an alternative.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.