使用 pymongo 从 mongodb 集合中提取文本字段并将其附加到 python 中的列表的代码
Code to extract text fields from a mongodb collection and append it to a list in python using pymongo
我创建了一个 if 语句来循环遍历 mongodb 个对象的 json 集合,并从每个对象中提取文本字段并将其附加到列表中。这是下面的代码。
appleSentimentText = []
for record in db.Apple.find():
if record.get('text'):
appleSentimentText.append(record.get("text"))
这很好用,但我有 20 个集合要执行此操作,我担心代码可能会开始变得有点混乱且难以管理,因为此代码有另外 19 个变体。我已经开始写一段代码来完成这个。首先,我创建了一个数组,其中包含 20 个集合的名称,如下所示。
filterKeywords = ['IBM', 'Microsoft', 'Facebook', 'Yahoo', 'Apple','Google', 'Amazon', 'EBay', 'Diageo',
'General Motors', 'General Electric', 'Telefonica', 'Rolls Royce', 'Walmart', 'HSBC', 'BP',
'Investec', 'WWE', 'Time Warner', 'Santander Group']
然后我在 if 语句中使用这个数组来循环遍历每个集合
for word in filterKeywords:
for record in db[word].find():
if db[word].get('text'):
我现在希望它根据集合名称创建一个列表变量(即如果集合是苹果,则为 AppleSentimentText,如果是 Facebook 集合,则为 FacebookSentimentText,等等),但我不确定下一步该怎么做。欢迎任何帮助
您可以使用 $exists and limit returned 字段到 "text" 所以它不需要遍历所有记录,在 pymongo 应该是这样的:
已编辑:
正如@BarnieHackett 指出的那样,您也可以过滤掉 _id
。
for word in filterKeywords:
for r in db[word].find({'text': {'$exists': True}}, {'text': 1, '_id': False}):
appleSentimentText.append(r['text'])
关键是使用$exists
然后将return字段限制为'text'
,不幸的是因为pymongoreturn s 包含 '_id'
和 'text'
字段的光标,您需要将其过滤掉。
希望这对您有所帮助。
我创建了一个 if 语句来循环遍历 mongodb 个对象的 json 集合,并从每个对象中提取文本字段并将其附加到列表中。这是下面的代码。
appleSentimentText = []
for record in db.Apple.find():
if record.get('text'):
appleSentimentText.append(record.get("text"))
这很好用,但我有 20 个集合要执行此操作,我担心代码可能会开始变得有点混乱且难以管理,因为此代码有另外 19 个变体。我已经开始写一段代码来完成这个。首先,我创建了一个数组,其中包含 20 个集合的名称,如下所示。
filterKeywords = ['IBM', 'Microsoft', 'Facebook', 'Yahoo', 'Apple','Google', 'Amazon', 'EBay', 'Diageo',
'General Motors', 'General Electric', 'Telefonica', 'Rolls Royce', 'Walmart', 'HSBC', 'BP',
'Investec', 'WWE', 'Time Warner', 'Santander Group']
然后我在 if 语句中使用这个数组来循环遍历每个集合
for word in filterKeywords:
for record in db[word].find():
if db[word].get('text'):
我现在希望它根据集合名称创建一个列表变量(即如果集合是苹果,则为 AppleSentimentText,如果是 Facebook 集合,则为 FacebookSentimentText,等等),但我不确定下一步该怎么做。欢迎任何帮助
您可以使用 $exists and limit returned 字段到 "text" 所以它不需要遍历所有记录,在 pymongo 应该是这样的:
已编辑:
正如@BarnieHackett 指出的那样,您也可以过滤掉 _id
。
for word in filterKeywords:
for r in db[word].find({'text': {'$exists': True}}, {'text': 1, '_id': False}):
appleSentimentText.append(r['text'])
关键是使用$exists
然后将return字段限制为'text'
,不幸的是因为pymongoreturn s 包含 '_id'
和 'text'
字段的光标,您需要将其过滤掉。
希望这对您有所帮助。