Skip to content

Instantly share code, notes, and snippets.

@arofiqimaulana
Last active February 29, 2024 04:18
Show Gist options
  • Select an option

  • Save arofiqimaulana/aac84df57defe4fa864473553295e6e8 to your computer and use it in GitHub Desktop.

Select an option

Save arofiqimaulana/aac84df57defe4fa864473553295e6e8 to your computer and use it in GitHub Desktop.
Query MongoDB via Python
import pymongo
import json
from datetime import datetime, timedelta, date, timezone
from pymongo import MongoClient
import datetime as dd
# 1. Create Connection
client = MongoClient(
host = '123.456.789',
port = int(27017), #
serverSelectionTimeoutMS = 3000,
username="admin",
password="123"
)
# 2. Delete record 4 days ago
four_days_ago = datetime.now() - timedelta(days=4)
criteria_delete = {"collectedAt":{"$lt":four_days_ago}} #lt = less than
result = collection.delete_many(criteria_delete)
# 3. Delete record in list
list_delete = ['a','c','d','v','k']
delete_result = collection.delete_many({
"server_id":
{"$in":list_delete}
})
# 4. get all record
criteria = {}
hasil_query = collection.find(criteria)
ls_dokumen = []
for dokumen in hasil_query:
ls_dokumen.append(dokumen)
# 5. Insert new key, if exist, update the record
for index,row in df.iterrows():
status_value = row["is_true_abuses"]
criteria = {"server_id": row["server_id"]}
result = collection.update_one(criteria, {"$set": {"is_true_abuses": status_value}}, upsert=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment