0

I am using python 3.6 and the latest version of mongod. This is my data base. Each document is called 'Module'.

I am trying to get all the message_logs of a specific module, that have a specific 'des' value.

I tried something like this:

filter_param = {
'info.id': module_id,
'message_logs': {'$elemMatch': {'des': dev_id}}
}
proj_param = {
    'message_logs.$': 1,
    '_id': 0
}
try:
    return db.modules.find_one(filter_param, projection=proj_param)['message_logs']
except Exception:
    return "Unconfigured device"

But I got only the first message_log that matched 'des'.

I would also like to know how to get the last matched element instead of the first one.

Nevo Mashiach
  • 79
  • 1
  • 4
  • If you want "multiple matches" then you use `$filter` just as shown in the linked examples. And before you ask *"..how with pymongo?"* then the answer is **exactly the same as the demonstrated JavaScript syntax** since python dict construction is basically identical. – Neil Lunn Apr 24 '18 at 04:37

1 Answers1

0

You're using find_one which will fetch only the first result that it finds. You should use find to get all the results.

i.e:

try:
    return db.modules.find(filter_param, projection=proj_param)['message_logs']
except Exception:
    return "Unconfigured device"
Sivaprasanna Sethuraman
  • 4,014
  • 5
  • 31
  • 60