Skip to content
Advertisement

Removing _id element from Pymongo results

I’m attempting to create a web service using MongoDB and Flask (using the pymongo driver). A query to the database returns documents with the “_id” field included, of course. I don’t want to send this to the client, so how do I remove it?

Here’s a Flask route:

JavaScript

This returns:

JavaScript

I thought it was a dictionary and I could just delete the element before returning it:

JavaScript

But that returns a TypeError:

JavaScript

So it isn’t a dictionary, but something I have to iterate over with each result as a dictionary. So I try to do that with this code:

JavaScript

Each object dictionary looks the way I’d like it to now, but the objects cursor is empty. So I try to create a new dictionary and after deleting _id from each, add to a new dictionary that Flask will return:

JavaScript

This just returns a dictionary with the first-level keys and nothing else.

So this is sort of a standard nested dictionaries problem, but I’m also shocked that MongoDB doesn’t have a way to easily deal with this.

The MongoDB documentation explains that you can exclude _id with

JavaScript

But that does nothing with pymongo. The Pymongo documentation explains that you can list the fields you want returned, but “(“_id” will always be included)”. Seriously? Is there no way around this? Is there something simple and stupid that I’m overlooking here?

Advertisement

Answer

To exclude the _id field in a find query in pymongo, you can use:

JavaScript

The documentation is somewhat missleading on this as it says the _id field is always included. But you can exclude it like shown above.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement