Pymongo将独特的数据插入Mongodb

时间:2017-12-11 08:43:33

标签: python mongodb facebook pymongo

我是Python,Facebook Graph API和MongoDB的新手。

我研究了有关插入MongoDB的在线资源。我不确定如何将从Facebook Graph API检索的不同且唯一的值插入到我的MongoDB数据库中。以下是我的代码:

def getPostReactionCount(reactions_data):
    reaction_count = {'LIKE' : 0, 'LOVE' : 0, 'HAHA' : 0, 'WOW' : 0, 'SAD' : 0, 'ANGRY' : 0}
    if 'reactions' in reactions_data:
        for x in reactions_data['reactions']['data']:
            if x['type'] == 'LIKE':
                    reaction_count['LIKE'] += 1
            elif x['type'] == 'LOVE':
                    reaction_count['LOVE'] += 1
            elif x['type'] == 'HAHA':
                    reaction_count['HAHA'] += 1
            elif x['type'] == 'WOW':
                    reaction_count['WOW'] += 1
            elif x['type'] == 'SAD':
                    reaction_count['SAD'] += 1
            elif x['type'] == 'ANGRY':
                    reaction_count['ANGRY'] += 1
    print 'reaction_count:'
    print reaction_count
    return reaction_count

posts_on_page = graph.get_object(page_id, fields = 'posts')
posts_data = json.loads(json.dumps(posts_on_page))


for i in posts_data['posts']['data']:
   dataPost = {}
   dataPost['post_id'] = i['id']
   dataPost['post_message'] = json.dumps(i['message']) 

   comments_in_posts  =  graph.get_object(post_id, fields = 'comments')

   dataPost['comments_data'] = json.loads(json.dumps(comments_in_posts))
   reactions_in_post = graph.get_object(post_id, fields = 'reactions')


   dataPost['reactions_data'] = json.loads(json.dumps(reactions_in_post))
   getPostReactionCount(reactions_data)

   print 'post_id:'
   print post_id
   print 'post_massage:'
   print post_massage
   print 'comments_data:'
   print comments_data                             
   print 'reactions_data:'
   print reactions_data

#insert process
collection.insert(dataPost)


# close the connection to MongoDB
connection.close()

我认为,关于collection.insert(dataPost)的行应该插入所有值,并且我可能有重复的值。

0 个答案:

没有答案