art049 / art049/odmantic

find_one() returns list of objects instead of one .. when using raw query to find a specific document in an embedded array of documents

Open
#104 2 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Python
Stars
1.2k
Forks
97
PR merge metrics
No merged PRs in 30d

Description

# Bug

I have a document like this:
```
{
"_id": ObjectId("user1"),
"addresses": [
{
"id": ObjectId("a1"),
"details": [....]
},
{
"id": ObjectId("a2"),
"details": [....]
}
],
}
```
I want to get the details of document `a1` only.

### Current Behavior
When using this code, it returns a document with the full embedded array
```
address = await engine.find_one(User, {"_id": ObjectId("user1"),
"addresses": {
"$elemMatch": {
"id": ObjectId("a1")
}
}})
```
It returns:
`{ "_id" : ObjectId("user1"), "addresses" : [ { "id" : ObjectId("a1"), "details" : [....]}, { "id" : ObjectId("a2"), "details" : [....]}, .... ... ] }`

### Expected behavior

When I use the mongo shell:
`db.users.find({_id: ObjectId("user1")}, {addresses: { $elemMatch: {"id": ObjectId("a1")} }})`
It returns:
`{ "_id" : ObjectId("user1"), "addresses" : [ { "id" : ObjectId("a1"), "details" : [....]} ] }`

### Environment

- ODMantic version: 0.3.2
- MongoDB version: 4.2.12
- Pydantic infos (output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`): 1.7.3

**Additional context**

Sorry If I missed something, It's my first time working with NoSQL

Contributor guide

Open the contributing guide

Research direction

Start at the engine.find_one() entry point and compare how its raw query handles the embedded addresses $elemMatch condition with the Mongo shell example. Done means a query targeting address a1 returns only that embedded address, rather than the full addresses array.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb, python
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.