# Fix TypeError: 'Collection' Object Is Not Callable in a PyMongo App

Yes. An agent reproduces the pymongo 4 TypeError, rewrites insert, remove and ensure_index to the methods that exist, runs the storage tests and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/fix-collection-object-is-not-callable/pymongo/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent clones the repository into its own cloud sandbox and reads the Mongo code first. In a Flask extension like muatik/flask-profiler, `flask_profiler/storage/mongo.py` holds a `Mongo` storage class whose `__init__` builds `pymongo.MongoClient(self.mongo_url)` and calls `self.collection.ensure_index([...])` on five keys, whose `insert` calls `self.collection.insert(measurement)`, whose `truncate` calls `self.collection.remove()` and whose `delete` calls `self.collection.remove({"_id": ObjectId(measurementId)})`; the read side uses `find().sort().skip().limit()` and `aggregate`. `storage/__init__.py` picks this class when `storage.engine` is `mongodb`, the README documents `MONGO_URL`, `DATABASE` and `COLLECTION`, `.travis.yml` installs `pymongo` and runs the suite with `FLASK_PROFILER_TEST_CONF=mongodb` against a `mongodb` service, and `tests/basetest.py` names the test database `flask_profiler_test` and collection `profiler`.

Then it reproduces the error without a server, because pymongo raises it before any connection is made. With the current pymongo 4, constructing the storage stops in `__init__`: `TypeError: 'Collection' object is not callable. If you meant to call the 'ensure_index' method on a 'Collection' object it is failing because no such method exists.` The same message names `insert` and `remove` when those lines are reached, since a pymongo 4 `Collection` turns any unknown attribute into a sub-collection and refuses to call it. A check of the class confirms what is gone and what replaced it: `insert`, `remove`, `ensure_index` and `count` are absent; `insert_one`, `delete_one`, `delete_many`, `create_index` and `count_documents` are present. On pymongo 3.13.0 the old `insert` still runs but prints `DeprecationWarning: insert is deprecated. Use insert_one or insert_many instead.`

The rewrite stays inside `mongo.py`: `ensure_index` becomes `create_index` with the same key list, `insert` becomes `insert_one` and returns whether `inserted_id` is set, `remove()` becomes `delete_many({})` and `remove({"_id": ...})` becomes `delete_one`, each returning the `acknowledged` flag the old code's truthiness check stood for. `find`, `sort`, `skip`, `limit` and `aggregate` are unchanged in pymongo 4, so the filter and summary methods need nothing. The methods keep their names and return types, so `flask_profiler.py` and the other storage engines are untouched.

To run the repository's own Mongo tests the sandbox needs a MongoDB; the agent installs Docker (`sudo apt-get install -y docker.io`, then starts `dockerd`), runs a `mongo` container on the default port, and runs `FLASK_PROFILER_TEST_CONF=mongodb python -m pytest tests`. It also runs the sqlite configuration as a control and reports what it finds there: in this repository tests fail on the current Flask because `flask_profiler.py` line 281 calls `before_first_request`, which Flask 3 removed. That is a separate bug, named in the pull request with its line and left for its own change.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "This Python project raises \"TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists\" after pymongo moved to version 4. Read requirements, setup.py and every file that uses pymongo first, and quote each call to a method pymongo 4 removed (insert, update, remove, ensure_index, count, find_and_modify and the like) with its file and line. Reproduce the error with the current pymongo release, then rewrite each call to its pymongo 4 method (insert_one or insert_many, update_one or update_many, delete_one or delete_many, create_index, count_documents, find_one_and_update), keeping each function's name, arguments and return value so callers do not change. If the tests need a MongoDB, install Docker in the sandbox, start a mongo container and run the suite against it; run any other storage configuration as a control. Report unrelated failures with their line without fixing them. Open a pull request that quotes the error before and the test output after.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request touching `flask_profiler/storage/mongo.py` only: one `create_index`, one `insert_one`, one `delete_many`, one `delete_one`, and no change to the read methods or to any caller. The description quotes the `TypeError` naming `ensure_index` from the current pymongo, the `DeprecationWarning` the same line printed on pymongo 3, the list of methods present and absent on the installed `Collection` class, and the test output against the Mongo container, with the Flask 3 failures in the sqlite control named separately.

A reviewer checks that each replacement keeps the old semantics: `delete_many({})` for a bare `remove()`, `delete_one` where an `_id` was given, and the boolean each method returned before. The run's record holds the pymongo probe and both test runs in full, so the method list and the results can be opened as the terminal sessions that produced them.

## Run it on every Sentry issue alert

A Sentry alert cannot carry the `Authorization: Bearer` header a Rush `webhook` trigger checks, because Sentry signs its requests its own way, so the alert goes to a handler on your server first. The handler sends this body to `POST /o/{org}/sessions` with the exception message and the first frame of the stack appended to `input`, and a `request_id` that is a UUID v5 of the Sentry issue id, so the same issue firing twice returns the run that is already working on it. When the run ends, the key's `webhook_url` receives `run.completed` or `run.failed` with the session URL and the pull request.

Where the error shows up in CI first, a step on failure can call a `webhook` trigger's URL directly with the secret Rush showed when the trigger was made, and the automation opens the pull request from the failing log.

## Why run it on Rush?

The message is confusing by design: pymongo 4 does not say `insert` was removed, it says a `Collection` is not callable, because the attribute lookup succeeded and produced a sub-collection. The agent explains that from a probe of the installed class in its own sandbox, with the list of what exists and what does not kept in the run's record, so the pull request replaces methods on evidence rather than on a guess at which release dropped what.

It is also a job that needs a database to prove, and standing one up on a laptop beside whatever else is running there is the part people skip. On Rush the run installs Docker, starts a Mongo container, runs the repository's own suite against it and keeps the output; the alert starts the run, and what comes back is a pull request with that output attached and an honest note on the unrelated failures it found on the way.

## Frequently asked questions

### Why does pymongo say the Collection is not callable instead of naming the missing method?

Because `db.coll.insert` is a valid expression in pymongo: attribute access on a `Collection` returns a sub-collection named `insert`, for databases that use dotted names. Calling that sub-collection is what fails, and pymongo 4 attaches the hint `If you meant to call the 'insert' method` to the `TypeError` so you can find the line.

### Does the rewrite change what gets stored?

No. `insert_one` writes the same document `insert` did, `create_index` builds the same index `ensure_index` did, and `delete_many({})` empties the collection as a bare `remove()` did. The return values are reduced to the booleans the callers already checked, so nothing above the storage layer changes.

### What if the project still needs pymongo 3 somewhere?

All the replacement methods exist on pymongo 3.x as well, which is why the agent uses them rather than a version check; the pull request works on both lines. The `DeprecationWarning` it quotes from pymongo 3 is the same change announced earlier.

### Why run the sqlite tests if the bug is in Mongo?

As a control. If the sqlite configuration fails too, the failure is not about pymongo, and in this repository that is what happens: Flask 3 removed `before_first_request`, which the extension still calls. The agent reports that with its line rather than folding a Flask migration into a pymongo fix.

## More PyMongo jobs

- [Fix "AttributeError: 'Cursor' object has no attribute 'count'" after a PyMongo upgrade](https://getrush.ai/run/fix-cursor-object-has-no-attribute-count/pymongo/)

## More jobs like this: Fix a bug from an alert

- [Fix "ImportError: cannot import name 'Mapping' from 'collections'"](https://getrush.ai/run/fix-collections-abc-import-error/python/)
- [Fix "ArgumentError: Column expression, FROM clause, or other columns clause element expected" on SQLAlchemy 2](https://getrush.ai/run/fix-column-expression-or-from-clause-expected/sqlalchemy/)
- [Fix "Compatibility with CMake < 3.5 Has Been Removed from CMake" After a CMake 4 Upgrade](https://getrush.ai/run/fix-compatibility-with-cmake-3-5-has-been-removed/cmake/)
- [Fix "the attribute `version` is obsolete" in a Docker Compose File](https://getrush.ai/run/fix-compose-version-obsolete-warning/docker-compose/)
- [Fix "Configuration via mocha.opts is DEPRECATED" and the --opts error on Mocha 8 and later](https://getrush.ai/run/fix-configuration-via-mocha-opts-is-deprecated/mocha/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
