discord.py how to remove documents in mongodb python

Question:

I’m trying to remove one and also able to remove all documents in a collection on mongodb and I’m not sure what to do.

@client.hybrid_command(name = "clearwarn", with_app_command=True, description="Delete a warn or all warns of a member", aliases=["clearwarns"])
@commands.guild_only()
@commands.is_owner()
@commands.has_permissions(moderate_members=True)
async def clearwarn(ctx, member: discord.Member = None, caseid = None):
    if member == None:
        await ctx.reply("A member is required")
    else:
        if caseid == None:
            check = list(warndb.warn_logs.find({ "user_id": member.id }))
            if check is None:
                await ctx.reply("This user doesn't have any warns to clear")
            else:
                warndb.warn_logs.delete_many(check)
                await ctx.reply(f"Removed all warnings from **{member.name}**")
                return
        else:
            try:
                check = list(warndb.warn_logs.find({"case_id": caseid}))
                warndb.warn_logs.delete_one(check)
                await ctx.reply(f"Removed 1 warning from **{member.name}**")
                return
            except:
                await ctx.reply("The case id you provided is invalid")
                return

I’m trying to make it so if someone just does ;clearwarn @member it deletes all the warns/documents that member has but if they do ;clearwarn @member (caseid) then it’ll delete only the warn/document that matches that case id.

randnum = random.randrange(1000, 999999)
        randnum2 = random.randrange(1000, 999999)
        warnid = f"{randnum}-{randnum2}"
        warndb.warn_logs.insert_one(
            {
                "guild_id": ctx.guild.id,
                "user_id": member.id,
                "moderator_id": ctx.author.id,
                "reason": str(reason),
                "case_id": warnid,
            }
        
        )

This is how I sorted the db. If you know please help me I’ve been struggling on this for a while

Asked By: TheRealKurumi

||

Answers:

To remove a document from a collection in MongoDB using python, you can use the delete_one() method. This method takes a query object that specifies the document to be deleted. For example:

import pymongo

# Connect to the MongoDB server
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Get a reference to the "test" database
db = client["test"]

# Get a reference to the "example" collection
collection = db["example"]

# Create the query object
query = {"name": "John Doe"}

# Delete the document
result = collection.delete_one(query)

# Print the number of documents deleted
print(result.deleted_count)

To delete all documents in a collection, you can use the delete_many() method. This method takes a query object that specifies the criteria for the documents to be deleted. For example:

import pymongo

# Connect to the MongoDB server
client = pymongo.MongoClient("mongodb://localhost:27017/")

# Get a reference to the "test" database
db = client["test"]

# Get a reference to the "example" collection
collection = db["example"]

# Create the query object
query = {}

# Delete all documents in the collection
result = collection.delete_many(query)

Print the number of documents deleted

print(result.deleted_count)
In both examples, the delete_one() and delete_many() methods return a DeleteResult object that contains the number of documents deleted. You can access this value using the deleted_count property.

I hope this helps!

Answered By: Puk
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.