I'm trying to query a MongoDB database to find all results which contains an specific ID:
My schema looks like this:
_id: xyz
ad_accounts: [{"name":"abc, "ads:{"campaings":[123, 4456, 574]}}]
I need to find all the results which contain 123 in "campaigns"
Here is a better image of the schema:

I've tried the following:
results = db.data.find({"ad_accounts.ads.campaigns": 123})
But it doesn't work since ad_accounts is an array, I've also tried with a loop:
for data in all_data:
for account in data['ad_accounts']:
if first_ad in account['ads']['campaigns]:
print("this is the one")
But I don't think it's the best.
Is there a built-in way to query nested data? Thanks
Going off your example, you can use this syntax:
>>> for match in collec.find({ "ad_accounts.0.ads.campaigns" : { "$in" : [123] } }):
... print(match)
...
{'_id': ObjectId('5adcd32690542e05e121bbdd'), 'ad_accounts': [{'name': 'abc', 'ads': {'campaigns': [123, 4456, 574]}}]}
$in is a command for matching any element from an array.
To reproduce this example with pymongo:
from pymongo import MongoClient
client = MongoClient()
test_db = client.test_db
collec = test_db.collec
val1 = {"ad_accounts": [{"name": "abc", "ads": {"campaigns": [123, 4456, 574]}}]}
val2 = {"ad_accounts": [{"name": "abc", "ads": {"campaigns": [999, 4456, 574]}}]}
collec.insert_many([val1, val2])
For a nested array, you would need elemMatch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With