如何使用查询遍历mongodb(JSON)文档

时间:2018-08-14 06:12:15

标签: json mongodb json-query

我的json文档是

{
"_id" : ObjectId("5b6049f845d12b6b62bf6fca"),
"original_query" : "",
}

我想遍历每个在相似字段中的人,然后使用python将其fb_id存储在列表中。

我是mnogodb和JSON的新手,任何潜在客户和帮助建立必要的直觉都将受到赞赏。

编辑:代码

import pymongo
from pymongo import MongoClient
import pprint


post=db.post
list_of_reactor_ids=[]
result=db.collection.find()
for doc in result:
   list_of_reactor_ids=[]
   for post in doc['posts']:
       for reactor in like['reactors']:
           list_of_reactor_ids.append(reactor[''])
print(list_of_reactor_ids)

1 个答案:

答案 0 :(得分:3)

您可以这样尝试:

client=MongoClient('mongodb://admin:Password1@localhost:27017/iitb')
db=client.iitb # this is you selecting the database 'iitb'
list_of_reactor_ids=[]
results = db.post.find() # 'post' is the name of collection
for doc in results:
    list_of_reactor_ids = []
    for post in doc['posts']:
        if 'like' in post:
            for reactor in post['like']['reactors']:
                list_of_reactor_ids.append(reactor['fb_id'])
print(list_of_reactor_ids)