python与mongo的find()问题

2013 年 3 月 31 日
 hilenlai
代码:
import os
import sys
import pymongo
import json
from pymongo import Connection
con = Connection()
db = con.test
collection = db.data
result = collection.find()
for value in result:
print value
print result

------------
for 循环得到的结果是:
{u'age': 25.0, u'_id': ObjectId('5157f624d86141fb9fbd9d08'), u'name': u'zhangsan', u'sex': 1.0}

{u'age': 25.0, u'_id': ObjectId('5157f625d86141fb9fbd9d09'), u'name': u'zhangsan', u'sex': 1.0}

{u'age': 25.0, u'_id': ObjectId('5157f625d86141fb9fbd9d0a'), u'name': u'zhangsan', u'sex': 1.0}

------------
result的结果是:
<pymongo.cursor.Cursor object at 0xb6f0de6c>



请问如何讲result的结果 直接打印出来 json 序列化呢?
像这种格式:
{ "people": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
]}
4597 次点击
所在节点    Python
11 条回复
dreampuf
2013 年 3 月 31 日
print json.dump(list(result))
013231
2013 年 3 月 31 日
json.dumps([dict((key, item[key]) for key in item if key != '_id') for item in doc.find()])
013231
2013 年 3 月 31 日
上面的答案要修改一下.
json.dumps([dict((key, item[key]) for key in item if key != '_id') for item in result])
ritksm
2013 年 3 月 31 日
亲们。。。要去掉_id直接在find里加参数不就得了。。。find({}, {"_id":0})
ritksm
2013 年 3 月 31 日
建议lz参考document。。。。http://api.mongodb.org/python/2.5/
hilenlai
2013 年 3 月 31 日
@dreampuf 这个结果不对撒~

@013231 这个可行!!得到一串
[{"age": 25.0, "name": "zhangsan", "sex": 1.0}, {"age": 25.0, "name": "zhangsan", "sex": 1.0}, {"age": 25.0, "name": "zhangsan", "sex": 1.0}, {"age": 25.0, "name": "zhangsan", "sex": 1.0}, {"age": 25.0, "name": "zhangsan", "sex": 1.0}, {"age": 25.0, "name": "zhangsan", "sex": 1.0}, {"age": 25.0, "name": "zhangsan", "sex": 1.0}, {"age": 25.0, "name": "zhangsan", "sex": 1.0}]


@ritksm 其实不是去掉id.. mongo查出来的不是bson嘛。 然后我想转化成json :)
binux
2013 年 3 月 31 日
@hilenlai 你显然没明白bson的b是什么

from bson import json_util as json
json.dump(list(result))
hilenlai
2013 年 3 月 31 日
@binux 的确是没有特别明白。。刚刚接触python才几天 :)我试试方法~~
ritksm
2013 年 3 月 31 日
@hilenlai bson是mongodb用来存储的格式。。。。pymongo查出来已经是dict了。。。。想知道是什么类型请用type(X)

http://d.pr/i/2cSz

BTW:Connection已经在新版本的pymongo中被弃用了。。。用MongoClient吧。。。
hilenlai
2013 年 3 月 31 日
@ritksm 多谢指教。

MongoClient 是python3.0的用法吗?
我还在用2.7呢
ooscrewyou
2013 年 4 月 9 日
@hilenlai 和Python版本沒關係 Connection已經deprecated了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://study.congcong.us/t/64571

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX