How to search the mongodb collection for dictionary keys nested in an array

I have some data in the mongodb database collection (I know which collection it views only the collection) with documents that look like this:

{ "_id" : ObjectId("52a93577dadf672b96062729"), "owner" : "user1", "files" : [ { "IyzkmGh4YGD61Tc3TJjaEY17hDldH" : "rws" } ] } { "_id" : ObjectId("52a92f43dadf672b96062725"), "owner" : "user2", "files" : [ { "tUI7RtvpHZklptvHVYssamlgHP6xs" : "rws" }, { "RsxRDQdXmHgmSLhMJ8tPxILxarruK" : "rws" }, { "IyzkmGh4YGD61Tc3TJjaEY17hDldH" : "rw" }, { "YA4to7HaB5Gm6JuZrwYrFit7IzvgO" : "rws" } ] } 

im trying to find a way to find all documents that have a specific dictionary key in an array of files inside them

as for the sample data, if I search using the line IyzkmGh4YGD61Tc3TJjaEY17hDldH , id, like both samples to match, since they both have a dictionary with this key in their list of files, how would I execute this query? im works with python motor to access mongodb. The reason is that I would like to delete these entries, when the files that they represent no longer exist, the Scheme is at my disposal, I can change it to make this search more reasonable,

+3
source share
1 answer

You can use dot notation in your query keys using the $exists operator to simply check for availability:

 db.test.find({'files.IyzkmGh4YGD61Tc3TJjaEY17hDldH': {'$exists': 1}}) 

To find all documents containing these files and delete them:

 db.test.update( {'files.IyzkmGh4YGD61Tc3TJjaEY17hDldH': {'$exists': 1}}, {'$pull': {'files': {'IyzkmGh4YGD61Tc3TJjaEY17hDldH': {'$exists': 1}}}}, multi=True) 
+5
source

All Articles