1

I have MongoDB documents that looks like this (unimportant data removed for clarity):

{
  "posts": [
    {
      "id": 1234,
      "comments": "I want this data!"
    },
    {
      "id": 4444,
      "comments" "foo"
    }
  ]
}

With only the knowledge that it's in the object with id=1234, how can I use Pymongo (Python 3) to return the "comments" value, ie "I want this data!"?

Thanks

Community
  • 1
  • 1
Bram
  • 79
  • 1
  • 8
  • Parse the JSON, iterate though the list for `d['id'] == 1234`, return `d['comments']`? – jonrsharpe Aug 02 '14 at 23:16
  • @jonrsharpe I should specify that there are many of these documents. I can't return them all and loop through them parsing the JSON. – Bram Aug 02 '14 at 23:19

1 Answers1

0

Loop over the list of dicts and find the dicts where id == 1234 then get the comment value:

 dic={
  "posts": [
    {
      "id": 1234,
      "comments": "I want this data!",
    },
    {
      "id": 4444,
      "comments": "foo",
    },
  ],
}
for d in dic["posts"]:
    if d.get("id") == 1234:
        print (d.get("comments"))
I want this data!

A list comp:

dic={
  "posts": [
    {
      "id": 1234,
      "comments": "I want this data!",
    },
    {
      "id": 4444,
      "comments": "foo",
    },
     {
      "id": 1234,
      "comments": "I want this data too!",
    },
  ],
}
print ([d.get("comments") for d in dic["posts"] if d.get("id") == 1234])
['I want this data!', 'I want this data too!']
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321