Using 'or' to find 'link.id' and 'link._id' may yield different results. #503
-
I use 1.17.0 version. resutl1 and resutl2 are both from separate searches. The result4 can search for my desired data using Why doesn't using Where am I doing wrong? import asyncio
from typing import List
from motor.motor_asyncio import AsyncIOMotorClient
from beanie import init_beanie, Document, PydanticObjectId, Link, WriteRules
from beanie.odm.operators.find.comparison import In, Eq
from beanie.odm.operators.find.logical import Or
from pydantic import Field
pyid1 = PydanticObjectId('6410918406f61093d4743fbb')
pyid2 = PydanticObjectId('641091948bdb9f7473dc5d40')
pyid3 = PydanticObjectId('641091948bdb9f7473dc5d41')
class UserGroupCollection(Document):
id: PydanticObjectId = Field(default_factory=PydanticObjectId)
name: str
class UserCollection(Document):
id: PydanticObjectId = Field(default_factory=PydanticObjectId)
user_group: List[Link[UserGroupCollection]] = Field(default_factory=list)
async def init():
client = AsyncIOMotorClient("mongodb://127.0.0.1:27017")
await init_beanie(
database=client.db_name,
document_models=[
UserCollection,
UserGroupCollection,
])
async def write():
await init()
group = []
for i in range(3):
group.append(await UserGroupCollection(name=f'group {i + 1}').create())
await UserCollection(id=pyid1, name='User1').create()
await UserCollection(id=pyid2, name='User2').create()
await UserCollection(id=pyid3, name='User3', user_group=[group[1]]).create()
await UserCollection(name='User4', user_group=[group[0]]).create()
await UserCollection(name='User5').create()
async def main():
await init()
group1 = await UserGroupCollection.find_one()
in_query = In(UserCollection.id, [pyid1, pyid2, pyid3])
eq_query = Eq(UserCollection.user_group.id, group1.id)
eq_id_query = Eq(UserCollection.user_group._id, group1.id)
result1 = await UserCollection.find(Or(in_query), fetch_links=True).to_list()
print(result1, end='\n\n')
result2 = await UserCollection.find(Or(eq_query), fetch_links=True).to_list()
print(result2, end='\n\n')
result3 = await UserCollection.find(Or(in_query, eq_query), fetch_links=True).to_list()
print(result3, end='\n\n')
result4 = await UserCollection.find(Or(in_query, eq_id_query), fetch_links=True).to_list()
print(result4, end='\n\n')
if __name__ == '__main__':
# asyncio.run(write())
asyncio.run(main()) If I don't use Link, there will be another result. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi. This happens because it is hard to understand aliases on the non-root layer. And |
Beta Was this translation helpful? Give feedback.
Hi. This happens because it is hard to understand aliases on the non-root layer. And
id
is just an alias over_id
in the database. I'm working on it, but this is a tricky problem and I can not promise that it will be implemented.