Skip to content

Instantly share code, notes, and snippets.

@luisdelatorre012
Created September 12, 2024 02:16
Show Gist options
  • Save luisdelatorre012/2598d727292738f6dfd230c748c9a7d3 to your computer and use it in GitHub Desktop.
Save luisdelatorre012/2598d727292738f6dfd230c748c9a7d3 to your computer and use it in GitHub Desktop.
mongo_debug.py
#Use explicit comparison in aggregation:
#Let's try using the aggregation framework with explicit type checking:
rom bson import Int64
pipeline = [
{
"$match": {
"$expr": {
"$and": [
{"$eq": [{"$type": "$a"}, "long"]}, # Ensure it's Int64
{"$gte": ["$a", Int64(100)]}
]
}
}
},
{"$limit": 5}
]
results = list(collection.aggregate(pipeline))
print("Results from aggregation:")
for doc in results:
print(f"_id: {doc['_id']}, a: {doc['a']}, type: {type(doc['a'])}")
#Verify index usage:
#Let's ensure the query is using an index correctly:
from bson import Int64
query = {"a": {"$gte": Int64(100)}}
explanation = collection.find(query).explain()
print("Query explanation:")
print(f"Using index: {explanation.get('queryPlanner', {}).get('winningPlan', {}).get('inputStage', {}).get('indexName')}")
print(f"Documents examined: {explanation.get('executionStats', {}).get('totalDocsExamined')}")
print(f"Keys examined: {explanation.get('executionStats', {}).get('totalKeysExamined')}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment