如何在 mongodb 集合中搜索嵌套在数组中的字典键 [英] how to search through a mongodb collection for dictionary keys nested in array

查看:77
本文介绍了如何在 mongodb 集合中搜索嵌套在数组中的字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mongodb 数据库集合中有一些数据(我知道是哪个集合,所以我只查看集合),文档如下所示:

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

喜欢示例数据,如果我使用字符串 IyzkmGh4YGD61Tc3TJjaEY17hDldH,id 喜欢两个样本匹配,因为它们的文件列表中都有一个带有该键的字典,我将如何执行此查询?我正在使用 python 电机访问 mongodb.原因是当它们代表的文件不再存在时,我想删除这些条目,架构由我支配,我可以更改它以使这种搜索更加合理,

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,

推荐答案

您可以在查询键中使用点表示法来执行此操作,使用 $exists 运算符来检查是否存在:

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)

这篇关于如何在 mongodb 集合中搜索嵌套在数组中的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆