Pymongo 的问题:想要将新字段添加到具有不同值的现有数据库,但所有条目结果都是相同的

Problem with Pymongo : Want to add new fields to existing db with different values but all entries turn out to be the same

我有一个评论数据库,想在我的数据库中创建一个新字段来指示评论是否包含与“pool”相关的词。

import re
import pandas as pd
from pymongo import MongoClient

client = MongoClient()

db = client.Hotels_Copenhagen
collection = db.get_collection("hotel_review_table")

data = pd.DataFrame(list(collection.find()))

def common_member(a, b):
    a_set = set(a)
    b_set = set(b)
    if a_set & b_set:
        return True
    else:
        return False

pool_set = {"pool","swim","swimming"}


for single_review in data.review_text:
    make_it_lowercase = str(single_review).lower()
    tokenize_it = re.split("\s|\.|,", make_it_lowercase)
    pool_mentioned = common_member(tokenize_it, pool_set)
    db.hotel_review_table.update_one({}, {"$set":{"pool_mentioned": pool_mentioned}})

在 python 中,我已经统计了包含与“泳池”相关的词语的评论数量,结果我的评论中有 1k/ 50k 谈论泳池。

我通过将 db.hotel_review_table.update_one 行移动到循环中解决了我之前发布的到处都获得相同条目的问题。

至此主要问题解决。但是,像这样更新数据库需要相当长的时间。有没有其他方法可以让它更快?

您在实现 MongoDB 中开箱即用的功能时遇到了很多麻烦。您需要使用 text indexes.

创建文本索引(在MongoDBshell):

db.hotel_review_table.createIndex( { "single_review": "text" } )

然后您的代码将提炼为:

from pymongo import MongoClient

db = MongoClient()['Hotels_Copenhagen']

for keyword in ['pool', 'swim', 'swimming']:
    db.hotel_review_table.update_many({'single_review': keyword}, {'$set': {'pool_mentioned': True}})

请注意,在未提及的情况下,这不会将值设置为 false;如果确实需要这样做,您可以编写另一个更新以将任何不正确的值设置为假。