Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Index on Link Field Not Being Used in Beanie Queries #1131

Open
parsa-pico opened this issue Feb 23, 2025 · 0 comments
Open

[BUG] Index on Link Field Not Being Used in Beanie Queries #1131

parsa-pico opened this issue Feb 23, 2025 · 0 comments

Comments

@parsa-pico
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant