Python2.7 - 如何读取MongoDB集合中的特定字段

时间:2016-11-16 15:54:27

标签: python mongodb

我有一些数据存储在我的集合中,这是一个通过shell获得的示例。 (请忽略文本的语言。)

{
    "_id" : ObjectId("581ab1811d41c814004f4d16"),
    "created_time" : "2016-11-02T19:48:41+0000",
    "message" : "Acabaram de assaltar o carro de um colega nosso em Itabaiana\nno zangue, ele é de Aracaju e foi passear em Itabaiana.Gol G6 prata 2013 placa OER-5474.\n",
    "id" : "400728540046889_1107668596019543"
}

在这种情况下,我只需要获取"message"字段中包含的文本,因为我需要在这些文本中执行多个操作。因此,过程如下:在我的集合中,我必须获取字段"message"中的所有文本执行操作,然后将此"message"返回到其正确的位置以及其他属性。到目前为止我的代码:

# -*- coding: utf-8 -*-
import preprocessing
import pymongo
import json
from pymongo import MongoClient
from unicodedata import normalize
from preprocessing import PreProcessing


if __name__ == '__main__':
    client = MongoClient('localhost:27017')
    collection = client.facebook.dadosColetados1
    try:
        dbmessage = collection.find()
        for text in dbmessage:
            print text
    except Exception, e:
        print str(e)

我无法传递要在查找中使用的"message"属性,当我仅使用find()时,它会返回我的文字而不是像utf-8那样:

e7\xf5es institucionais para uma seguran\xe7a p\xfablica mais integrada em todo o Estado.\n\nO secret\xe1rio destacou a import\xe2ncia da manuten\xe7\xe3o do di\xe1logo entres as institui\xe7\xf5es.

这种情况的最佳方法是什么?

Edit1:@ jcmetz21提出的解决方案有效。

1 个答案:

答案 0 :(得分:1)

您可以查询数据库并设置投影,只需与"消息"相关联的值字段。键被返回。然后将消息放入列表中。

import pymongo

client = pymongo.MongoClient('localhost:27017')
db = client['db_name']

query = {'message': {'$exists': 1}}
projection = {'_id': 0, 'message': 1}

data = list(db['collection_name'].find(query, projection))

message_list = []
for message in data:
    for key, value in message.iteritems():
        message_list.append(value)

现在" message_list"将包含您的集合中的所有消息,您可以对数据执行任何操作:

message_list = [u'message1', u'message2', u'message3', etc.]

编辑#2(注意上面的更改):如果要保持与其相应消息关联的ID和时间戳,您可以执行以下操作...

在投影中,设置' id'和' created_time'键入1(' id':1,' created_time':1)并更改上面的代码:

message_list = [value for dict in data for key, value in dict.iteritems() if key == 'message']
id_list = [value for dict in data for key, value in dict.iteritems() if key == 'id']
timestamp_list = [value for dict in data for key, value in dict.iteritems() if key == 'created_time']

# to print all of your messages
for message in message_list:
    print message

现在,您可以看到所有消息并按照它们执行所需操作,无论是通过迭代更新所有消息还是通过索引更新一些消息。

然后,您可以将所有3个列表配对,以便了解哪些数据与哪些数据相关联。

pair_up = zip(message_list, id_list, timestamp_list)

for x, y, z in pair_up:
    print "The message " + x + " has id " + y + " and timestamp " + z