KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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: @app.route('/theobjects') def index(): objects = db.collection.find() return str(json.dumps({'results': list(objects)}, default = json_util.default, indent = 4)) This returns: { "results": [ { "whatever": { "field1": "value", "field2": "value", }, "whatever2": { "field3": "value" }, ... "_id": { "$oid": "..." }, ... } ]} I thought it was a dictionary and I could just delete the element before returning it: del objects['_id'] But that returns a TypeError: TypeError: 'Cursor' object does not support item deletion 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: for object in objects: del object['_id'] 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: new_object = {} for object in objects: for key, item in objects.items(): if key == '_id': del object['_id'] new_object.update(object) 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 <a href="http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+
Tags (comma-separated)
Save Edits
Cancel