一直試圖自己解決它,所以我們有以下宣告:
練習 5.1(代碼)使用存盤在 MongoDB 集合中的資料和評論,計數
進行評論的不同用戶的數量(即計算欄位reviewerID的不同值的數量)
至少給出一個差評(小于或等于 2 星)的不同用戶的數量
收到評論的不同書籍的數量(即計算欄位asin的不同值的數量)。
這是我的代碼:
n_users = len(db[reviews_collection].distinct("reviewerID"))
n_users_bad_rating = len(db[reviews_collection].distinct("reviewerID", {"overall": {"$lte": 2.0}}))
n_books = len(db[reviews_collection].distinct("asin"))
print(f"There are {n_users} distinct users.")
print(f"There are {n_users_bad_rating} distinct users who gave at least one bad rating (less or equal to 2 stars).")
print(f"There are {n_books} distinct books in the reviews.")
這是我得到的輸出:
有 3613 個不同的用戶。有 0 個不同的用戶給出了至少一個差評(小于或等于 2 星)。評論中有3807本不同的書。
集合中資料的示例:
{'_id': ObjectId('6252c21c2ee307d4d522af0a'),
'appreciation': 'liked',
'asin': 'B000R93D4Y',
'book_index': 0,
'helpful': [3, 3],
'overall': 5.0,
'reviewText': 'A strange world full of strange creatures, knights, and '
'beautiful maidens. The magical aspect of healing was a nice '
'touch.',
'reviewTime': '06 23, 2013',
'reviewerID': 'A195CNOUUIT4SU',
'summary': 'Great tale of dragons',
'train_val_test': 'train',
'unixReviewTime': 1371945600,
'user_index': 0}
問題:為什么我無法使用條件?我在筆記本中有其他練習,我被要求查詢資料庫,除非我嘗試指定條件,否則它作業得很好。當我使用回圈時,它告訴我有一個“TypeError:字串索引必須是 int”
uj5u.com熱心網友回復:
這是一個選項,如何通過聚合框架為總體 <=2 的 reviewerID 找到不同的值:
db.collection.aggregate([
{
$match: {
"overall": {
"$lte": 2.0
}
}
},
{
"$group": {
"_id": "TotalUnique",
"unique": {
"$addToSet": "$reviewerID"
}
}
}
])
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/457941.html
上一篇:輸入Mongoose驗證函式
下一篇:Mongodb:陣列中的多個物件
