How do I get projection$ to work in pymongo?
Naki Colson
I have a query which runs in a mongo
repl .
I have some files that look like this...
[{
"_id" : ObjectId("5b6b6959828619572d48a9da"),
"files" : [
{
"original_filename" : "test_file1.csv",
"s3_key" : "intake/uploads/3edc78aa-2275-45ad-afcb-23bf4a765591/test_file1.csv"
},
{
"original_filename" : "test_file2.csv",
"s3_key" : "intake/uploads/3edc78aa-2275-45ad-afcb-23bf4a765591/test_file2.csv"
}
],
"created_at" : ISODate("2018-08-08T22:06:17.366Z")
}]
In the mongo
repl I can do the following:
db.uploads.find({"_id": ObjectId("5b6b6959828619572d48a9da"), "files.original_filename": "test_file1.csv"}, {"files.$": 1})
I receive data exactly as I want:
{
"_id" : ObjectId("5b6b6959828619572d48a9da"),
"files" : [
{
"original_filename" : "test_file2.csv",
"s3_key" : "intake/uploads/3edc78aa-2275-45ad-afcb-23bf4a765591/test_file2.csv"
}
]
}
But after pymongo
I do this:
query = {
'_id': upload_id,
'files.original_filename': 'test_file1.csv'
}
projection = {'files.$': 1}
result = list(self.uploads.find(query, projection))
The result is wrong:
[{'files': {}, '_id': ObjectId('5b6b6959828619572d48a9da')}]
Why? ! ?
Naki Colson
query = {
'_id': upload_id
}
projection = {
'files': {
'$elemMatch': {
'original_filename': original_filename
}
}
}
result = list(self.uploads.find(query, projection))
I switched to this projection and seemed to get the data I wanted. I'm still wondering why, and if there are other better ways to do this.