Use MongoDB with custom commands bot
lets see how we can use mongodb database with slash commands
Md Shahriyar Alam
2 years ago
Storing data with MongoDB and SlashMongo
Slash commands are stateless by default — every run starts fresh. SlashMongo
changes that: it hands your command a real MongoDB collection it can read from
and write to, so you can build economies, leveling systems, warns, inventories
— anything that needs to remember data between runs.
Connecting to a collection
Call SlashMongo(db_name, collection_name). The collection name is optional and
defaults to main.
# a collection named "users" in the "economy" database
users = SlashMongo("economy", "users")
# no collection name → defaults to "main"
store = SlashMongo("economy")Inserting documents
Use insert_one for a single document, or insert_many to add a whole list at
once.
users = SlashMongo("economy", "users")
# one document
users.insert_one({"user_id": user.id, "coins": 100})
# many at once
users.insert_many([
{"user_id": 1, "coins": 50},
{"user_id": 2, "coins": 75},
])Reading data
find_one returns the first matching document (or nothing). find returns a
list of every match — capped at 10,000 documents so a broad query can't
exhaust memory.
# a single document
doc = users.find_one({"user_id": user.id})
respond(f"You have {doc['coins']} coins")
# a list of documents
rich = users.find({"coins": {"$gte": 100}})
respond(f"{len(rich)} rich users")Updating documents
update_one edits the first match, update_many edits all of them. Pass
upsert=True to create the document when it does not exist yet — perfect for
"add coins to a user I've never seen".
# add 10 coins to one user
users.update_one({"user_id": user.id}, {"$inc": {"coins": 10}})
# create the user if they don't exist yet
users.update_one(
{"user_id": user.id},
{"$inc": {"coins": 10}},
upsert=True,
)
# give everyone 5 coins
users.update_many({}, {"$inc": {"coins": 5}})Deleting documents
delete_one removes the first match; delete_many removes every match. An empty
filter {} matches everything — use it carefully.
users.delete_one({"user_id": user.id})
# clear out everyone with no coins
users.delete_many({"coins": {"$lte": 0}})Aggregations
aggregate runs a full pipeline for leaderboards, grouping and stats. It returns
a list (also capped at 10,000). For safety the $out and $merge stages are
blocked — including when nested inside $lookup or $facet — because they could
write outside your server's scope.
# top 10 richest users
top = users.aggregate([
{"$sort": {"coins": -1}},
{"$limit": 10},
])
loop(top, index):
member = get_member(top[index]['user_id'])
respond(f"#{index + 1} — {member.mention}: {top[index]['coins']}")Loading comments…
Need help?
Have a question, a suggestion, or stuck on something? Reach out — we're happy to help.