如何使用PyMongo创建MongoDB通配符文本索引?
Got it, I totally get where you're coming from—you know the MongoDB Shell syntax for wildcard text indexes, and you're familiar with PyMongo's basic create_index method, but connecting those two can feel a bit tricky at first. Let's fix that!
The Short Answer
PyMongo's create_index method maps directly to the MongoDB Shell syntax—you just need to structure the wildcard text index definition correctly as a list of tuples (which is PyMongo's standard way to define indexes).
Here's the exact code you need:
from pymongo import MongoClient # Establish your connection (adjust the URI as needed for your setup) client = MongoClient("mongodb://localhost:27017/") db = client["your_target_database"] collection = db["your_target_collection"] # Create the wildcard text index collection.create_index([("$**", "text")])
Breaking It Down
Let's compare this to the MongoDB Shell command you already know:
db.collection.createIndex( { "$**": "text" } )
In PyMongo, the create_index method expects the index definition as a list of tuples, where each tuple follows the format (field_name, index_type). For a single-field wildcard text index, that list only needs one tuple: ("$**", "text")—this directly mirrors the { "$**": "text" } document from the Shell.
Optional: Custom Index Name
If you want to set a human-readable custom name for your index (instead of letting MongoDB generate an auto-named one), just add the name parameter:
collection.create_index([("$**", "text")], name="custom_wildcard_text_index")
Verify the Index Was Created
To confirm everything worked as expected, you can list all indexes on the collection:
# Print all indexes for the collection for index in collection.list_indexes(): print(index)
You should see your wildcard text index in the output, either with the auto-generated name or your custom one.
内容的提问来源于stack exchange,提问作者Deepak Aggarwal

