mike
mike

Reputation: 907

how to search through a mongodb collection for dictionary keys nested in array

i have some data in a mongodb database collection (i know which collection so im only looking through the collection ) with documents that looks 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 think of a way to find all documents that have a particular dictionary key in the array of files within them

like for the sample data if i search using the string IyzkmGh4YGD61Tc3TJjaEY17hDldH, id like both samples to match since they both have a dictionary with that key in their list of files, how would i perform this query? im working with the python motor to access mongodb. The reason is i'd like to delete these entries when files they represent are no longer in existence, The schema is at my disposal, i could change it to make this kind of search more sane,

Upvotes: 5

Views: 10691

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

You can use dot notation in your query keys to do this, using the $exists operator to just check for existence:

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

To find all docs that contain those files and remove them:

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

Upvotes: 11

Related Questions