2010-03-22 6 views
3

J'ai une collection d'articles en MongoDB qui a la structure suivante:documents de filtrage contre une clé de dictionnaire dans 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" 
} 

Si je voulais écrire une requête qui avait l'air pour tous les articles qui avaient au moins 1 géographie tag, comment ferais-je cela? J'ai essayé d'écrire db.articles.find ({'tags': 'geography'}), mais cela ne semble pas fonctionner. J'ai également pensé à changer le paramètre de recherche en 'tags.geography', mais j'ai un peu de temps pour trouver ce que serait le prédicat de recherche.

Répondre

7

Si le champ « géographie » n'existe pas quand il n'y a pas de balises dans (ie, il est créé lorsque vous ajoutez un emplacement), vous pouvez faire:

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

Si elle n'existe et est vide (c.-à-"geography" : []), vous devez ajouter un champ geography_size ou quelque chose et de le faire:

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

Il y a plus d'informations sur les requêtes à http://www.mongodb.org/display/DOCS/Advanced+Queries

+0

brillant! Merci Kristina! – Thomas

Questions connexes