Describe the bug
I encountered an issue with Beanie where the index on a Link field (specifically for the major field in my Course document) does not seem to be used during queries. However, the index works correctly when using a native MongoDB query with DBRef. Below is the code and a comparison of the behavior. i found the difference by checking usage of major field index (inside course collection) in mongodb compass
To Reproduce
from beanie import Document, PydanticObjectId, init_beanie, Link
from motor.motor_asyncio import AsyncIOMotorClient
from bson import DBRef, ObjectId
import asyncio
class Major(Document):
majorId: str
majorName: str
class Settings:
name = "majors"
class Course(Document):
courseId: str
major: Link[Major]
class Settings:
name = "uni_courses"
indexes = ['major']
client = None
async def init():
global client
client = AsyncIOMotorClient("mongodb://localhost:27017")
await init_beanie(client.test_db, document_models=[Major, Course])
async def insert_data():
major = Major(majorId="123", majorName="CS")
await major.insert()
course = Course(courseId="CS101", major=major)
await course.insert()
async def query_with_beanie():
courses = await Course.find_many(Course.major.id == PydanticObjectId("67bb97e9a033f22d877df9e5")).to_list()
async def query_with_native_mongo():
global client
courses = await client.test_db.uni_courses.find({"major": DBRef('Major', ObjectId("67bb97e9a033f22d877df9e5"))}).to_list(length=None)
async def main():
await init()
await insert_data()
await query_with_beanie()
await query_with_native_mongo()
asyncio.run(main())
Expected behavior
The index on the major field should be used when querying via Beanie, and MongoDB Compass should show an increase in index usage.
Additional context
This issue seems to be related to how Beanie handles Link fields and indexing. The native query works fine, but the Beanie query does not utilize the index.
Describe the bug
I encountered an issue with Beanie where the index on a Link field (specifically for the major field in my Course document) does not seem to be used during queries. However, the index works correctly when using a native MongoDB query with DBRef. Below is the code and a comparison of the behavior. i found the difference by checking usage of major field index (inside course collection) in mongodb compass
To Reproduce
Expected behavior
The index on the major field should be used when querying via Beanie, and MongoDB Compass should show an increase in index usage.
Additional context
This issue seems to be related to how Beanie handles Link fields and indexing. The native query works fine, but the Beanie query does not utilize the index.