0

I have a collection containing country records, I need to find particular country with uid and it's countryId

Below is the sample collection data:

{
"uid": 15024,

"countries": [{
        "countryId": 123,
        "popullation": 45000000

    },
    {
        "countryId": 456,
        "poppulation": 9000000000
    }
]

},
{
"uid": 15025,

"countries": [{
        "countryId": 987,
        "popullation": 560000000

    },
    {
        "countryId": 456,
        "poppulation": 8900000000
    }
]

}

I have tried with below query in in python but unable to find any result:

foundRecord = collection.find_one({"uid" : 15024, "countries.countryId": 456})

but it return None.

Please help and suggest.

Pradeep
  • 475
  • 1
  • 4
  • 18
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Ashh Sep 20 '18 at 18:05

2 Answers2

0

I think following will work better :

foundRecord = collection.find_one({"uid" : 15024,
                                   "countries" : {"$elemMatch" : { "countryId" : 456 }})
CZ54
  • 5,488
  • 1
  • 24
  • 39
0

Are you sure you're using the same Database / Collection source?

Seems that you're saving results on another collection.

I've tried to reproduce your problem and it works on my mongodb ( note that I'm using v4)

EDIT: Would be nice to have the piece of code where you're defining "collection"

David Garaña
  • 915
  • 6
  • 8