5

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,

1 Answer 1

11

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)
Sign up to request clarification or add additional context in comments.

3 Comments

any idea how i would delete the entry(s)? i tried different variants of this and it did not work: db.user_data.update({'projects.IyzkmGh4YGD61Tc3TJjaEY17hDldH': {'$exists': 1}},{ $pull : { 'projects' : 'IyzkmGh4YGD61Tc3TJjaEY17hDldH' }})
awesome, it worked, i had no idea i could refer to the value of the document i just found with {'$exists':1}, mongodb is pretty cool. where is this use case explained, i could not find this in here: docs.mongodb.org/manual/reference/operator/query/exists you certainly understand mongodb
@mike You're not referring to the value of the doc you just found with $exists, you're simply using it to identify the elements to $pull from files, in the same way you used it to identify the documents to update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.