python - 根据 MongoDB 中的字典键过滤文档

标签 python mongodb pymongo

我在 MongoDB 中有一组文章,其结构如下:

{
    'category': 'Legislature', 
    'updated': datetime.datetime(2010, 3, 19, 15, 32, 22, 107000), 
    'byline': None, 
    'tags': {
        'party': ['Peter Hoekstra', 'Virg Bernero', 'Alma Smith', 'Mike Bouchard', 'Tom George', 'Rick Snyder'], 
        'geography': ['Michigan', 'United States', 'North America']
    }, 
    'headline': '2 Mich. gubernatorial candidates speak to students', 
    'text': [
        'BEVERLY HILLS, Mich. (AP) \u2014 Two Democratic and Republican gubernatorial candidates found common ground while speaking to private school students in suburban Detroit', 
        "Democratic House Speaker state Rep. Andy Dillon and Republican U.S. Rep. Pete Hoekstra said Friday a more business-friendly government can help reduce Michigan's nation-leading unemployment rate.", 
        "The candidates were invited to Detroit Country Day Upper School in Beverly Hills to offer ideas for Michigan's future.", 
        'Besides Dillon, the Democratic field includes Lansing Mayor Virg Bernero and state Rep. Alma Wheeler Smith. Other Republicans running are Oakland County Sheriff Mike Bouchard, Attorney General Mike Cox, state Sen. Tom George and Ann Arbor business leader Rick Snyder.', 
        'Former Republican U.S. Rep. Joe Schwarz is considering running as an independent.'
    ], 
    'dateline': 'BEVERLY HILLS, Mich.', 
    'published': datetime.datetime(2010, 3, 19, 8, 0, 31), 
    'keywords': "Governor's Race", 
    '_id': ObjectId('4ba39721e0e16cb25fadbb40'), 
    'article_id': 'urn:publicid:ap.org:0611e36fb084458aa620c0187999db7e', 
    'slug': "BC-MI--Governor's Race,2nd Ld-Writethr"
}

如果我想编写一个查询来查找所有至少有 1 个地理标签的文章,我该怎么做?我试过写 db.articles.find( {'tags': 'geography'} ),但这似乎不起作用。我也考虑过将搜索参数更改为“tags.geography”,但我很想弄清楚搜索谓词是什么。

最佳答案

如果“地理”字段在其中没有任何标签时不存在(即,它是在您添加位置时创建的),您可以这样做:

db.articles.find({tags.geography : {$exists : true}})

如果它确实存在并且为空(即,"geography": []),您应该添加一个 geography_size 字段或其他内容并执行以下操作:

db.articles.find({tags.geography_size : {$gte : 1}})

关于查询的更多信息,请访问 http://www.mongodb.org/display/DOCS/Advanced+Queries

关于python - 根据 MongoDB 中的字典键过滤文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2495932/

相关文章:

python - 是否可以导入函数内定义的类?

node.js - 如何通过 ID 数组查找文档并通知不匹配的文档

mongodb - 在聚合管道期间对列表索引进行平均?

python - 我可以在没有任何转储的情况下 pickle 字符串吗?

python - 使用 Waitress、Flask 和 Python 将请求记录到文件

python - Google Cloud Dataflow 从字典写入 CSV

mongodb - 删除大小大于特定值的文档

java - 如何在 Java Mongo 中指定多个条件

python - PyMongo find_one 不返回现有条目

python - 您可以将文本搜索的权重传递给 PyMongo 中的 create_index 吗?