Skip to content

Instantly share code, notes, and snippets.

@VITIMan
Last active January 3, 2018 15:10
Show Gist options
  • Save VITIMan/6f69c67748b8a4c032b2b1d7e1ad2945 to your computer and use it in GitHub Desktop.
Save VITIMan/6f69c67748b8a4c032b2b1d7e1ad2945 to your computer and use it in GitHub Desktop.
PyMongo snippets
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)
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