I have this example MongoDB entry in a users
DB:
JavaScript
x
12
12
1
{
2
_id: xxx,
3
name: "name",
4
files:[{
5
fileName: "test",
6
size: 654
7
},
8
{fileName: "test2",
9
size: 50
10
}]
11
}
12
And I’m using Pymongo to query the file named “test”:
users.find_one({'files.filename':"test"})
How can I limit the output from Pymongo, so it only gives me the dict
where “test” is contained? In other words, I want it to output this:
JavaScript
1
5
1
{
2
fileName: "test",
3
size: 654
4
}
5
Advertisement
Answer
Here’s one way you could do it.
JavaScript
1
21
21
1
db.users.aggregate([
2
{
3
"$match": {
4
"files.fileName": "test"
5
}
6
},
7
{
8
"$replaceWith": {
9
"$first": {
10
"$filter": {
11
"input": "$files",
12
"as": "file",
13
"cond": {
14
"$eq": ["$$file.fileName", "test"]
15
}
16
}
17
}
18
}
19
}
20
])
21
Try it on mongoplayground.net.