从Pymongo结果中删除_id元素 [英] Removing _id element from Pymongo results
问题描述
我正在尝试使用MongoDB和Flask(使用pymongo驱动程序)创建Web服务.当然,对数据库的查询将返回包含"_id"字段的文档.我不想将其发送给客户端,那么如何删除它?
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?
这是一条烧瓶路线:
@app.route('/theobjects')
def index():
objects = db.collection.find()
return str(json.dumps({'results': list(objects)},
default = json_util.default,
indent = 4))
这将返回:
{
"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']
但是返回TypeError:
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']
每个对象字典看起来都像我现在想要的那样,但是对象光标为空.因此,我尝试创建一个新字典,并从每个字典中删除_id之后,将其添加到Flask将返回的新字典中:
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.
所以这是一个标准的嵌套字典问题,但令我感到震惊的是MongoDB没有一种轻松解决此问题的方法.
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.
MongoDB文档解释说,您可以排除_id与
The MongoDB documentation explains that you can exclude _id with
{ _id : 0 }
但这与pymongo无关. Pymongo文档解释说您可以列出要返回的字段,但(("_id"将始终包含))".严重地?有没有办法解决这个问题?我在这里忽略了一些简单而愚蠢的事情吗?
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?
推荐答案
要在pymongo的查找查询中排除_id
字段,可以使用:
To exclude the _id
field in a find query in pymongo, you can use:
db.collection.find({}, {'_id': False})
此文档在说服力上有些误导,因为它说总是包含_id
字段.但是您可以像上面显示的那样排除它.
The documentation is somewhat missleading on this as it says the _id
field is always included. But you can exclude it like shown above.
这篇关于从Pymongo结果中删除_id元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!