from pymongo import MongoClient, errors
# MongoDB connection settings
mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"
source_collection_name = "tweets"
try:
client = MongoClient(mongo_uri, serverSelectionTimeoutMS=5000)
db = client[database_name]
source_collection = db[source_collection_name]
# Define query to filter tweets related to KLM (tweets made by KLM or mentioning KLM)
query = {
"$or": [
{"json_data.user.id": 56377143}, # Tweets made by KLM
{"json_data.entities.user_mentions.id": 56377143} # Tweets mentioning KLM
]
}
# Count the number of tweets related to KLM
klm_tweet_count = source_collection.count_documents(query)
print("Number of tweets related to KLM:", klm_tweet_count)
except errors.ServerSelectionTimeoutError as err:
print("Failed to connect to MongoDB server:", err)
except errors.PyMongoError as err:
print("An error occurred while working with MongoDB:", err)
finally:
client.close()
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter