Home > Software engineering >  How to use "hint" parameter with pymongo's delete_many()
How to use "hint" parameter with pymongo's delete_many()

Time:11-12

Per https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html, for delete_many(), hint was added in 3.11. Our pymongo:

>>> pymongo.__version__
'3.12.1'

We are trying to use this parameter to more quickly delete rows from our database:

from pymongo import MongoClient
from pymongo import ASCENDING, DESCENDING, TEXT
import os
MONGO_URI = os.getenv('MONGO_URI')

# connect to db
cluster = MongoClient(MONGO_URI)
db = cluster["cbbap"]

# set function parameter values
our_filter = { 'competitionId': { '$in': [30629, 30630] } }
our_hint = { 'competitionId': 1 } # competitionId is an index in our collection
table_name = 'our_table'

# this line works just fine
db[table_name].delete_many(filter = our_filter)

We run into problems when we try

# this line does not work
db[table_name].delete_many(filter = our_filter, hint = our_hint)

Returning Error: TypeError: passing a dict to sort/create_index/hint is not allowed - use a list of tuples instead. did you mean [('competitionId', 1)]?

So we try:

# does not work
our_hint = [('competitionId', 1)]
db[table_name].delete_many(filter = our_filter, hint = our_hint)

Returning Error: pymongo.errors.OperationFailure: BSON field 'delete.deletes.hint' is an unknown field. And we also tried

# does not work
db[table_name].delete_many(filter = our_filter, hint = 'competitionId')

as the docs say a string can be passed, however this does not work either, returning the same error pymongo.errors.OperationFailure: BSON field 'delete.deletes.hint' is an unknown field..

How can we use the hint parameter with pymongo's delete_many function? What are we doing wrong here?

CodePudding user response:

This works fine with me.

hint in DeleteMany is only supported on MongoDB 4.4 and above.

@app.get("/delete/{id}")
async def root(id: int):
    db = get_database()
    our_filter = { 'competitionId': { '$in': [30629, 30630] } }
    our_hint = [('competitionId', 1)]
    c = db['key'].delete_many(filter = our_filter,hint = our_hint)
    return {"message": c.deleted_count}
  • Related