【问题标题】:How to traverse the mongodb(JSON) document using queries如何使用查询遍历 mongodb(JSON) 文档
【发布时间】:2018-08-14 06:12:14
【问题描述】:

我的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)

【问题讨论】:

  • 你想用javascript遍历这个吗?
  • 不是,我是用python来遍历的

标签: json mongodb json-query


【解决方案1】:

你可以这样尝试:

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)

【讨论】:

  • 我试过这种方式,但我得到 TypeError:'Collection' object is not iterable on the first iteration of posts
  • @Dumb 来自 mongo 的 json 文档的类型是什么?使用 type(doc) 查找
  • @Dumb 编辑了代码 - 我想你已经选择了两次收藏。请注意您必须如何选择 DB,然后选择 Collection,然后您可以在 collection 上运行“查找”
  • @Dumb 我犯了一个错误。代码已更正 - 请再试一次;)
  • 我添加了一个测试 - 见上文
猜你喜欢
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2020-11-06
  • 1970-01-01
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多