-
-
Save mieitza/f37d3255fea0f17c13f77a0783e17b87 to your computer and use it in GitHub Desktop.
PyMongo snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def reaching_max_messages(current_hour_bitrange): | |
""" | |
from https://stackoverflow.com/a/29281409 | |
""" | |
# https://stackoverflow.com/a/29281409 | |
# https://docs.mongodb.com/manual/reference/operator/query/bitsAllSet/ | |
pipeline = [ | |
{ | |
"$addFields": { | |
"max_messages": { | |
"$cmp": ["$limit_messages", | |
"$current_messages"] | |
} | |
} | |
}, | |
{ | |
"$match": { | |
"max_messages": 1 | |
} | |
} | |
] | |
return db.user.aggregate(pipeline) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
from pymongo import MongoClient, UpdateOne | |
def bulk_upsert(some_ids, value_unique): | |
""" | |
https://stackoverflow.com/a/36213728 | |
Upsert elements given a list of ids and adding to set some information non-duplicated | |
""" | |
db.msisdn.bulk_write([ | |
UpdateOne( | |
{"some_id": id}, | |
{"$addToSet": {"some_array": value_unique}, | |
"$set": {"modification_date": datetime.datetime.utcnow()}}, | |
upsert=True) for id in some_ids]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment