Is possible to query mongodb on array keys?

10,283

Solution 1

You can use $exists for this:

> db.things.insert({'type': 'Information', 'ids':{'id1': 123, 'id2': 456}})
> db.things.insert({'type': 'Information', 'ids':{'id1': 746, 'id2': 456}})
> db.things.insert({'type': 'Information', 'ids':{'id2': 456, 'id3': 936}})

> db.things.find({'ids.id1': {'$exists': true}})
{ "_id" : ObjectId("4dd3c706938307861ed610dd"), "type" : "Information", "ids" : { "id1" : 123, "id2" : 456 } }
{ "_id" : ObjectId("4dd3c7a1938307861ed610de"), "type" : "Information", "ids" : { "id1" : 746, "id2" : 456 } }

Solution 2

Thanks to scoates in #mondodb channel, it's possible to do that with exists function : http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24exists

db.Information.find({"ids.id1":{$exists:true}});
Share:
10,283
Brice Favre
Author by

Brice Favre

French Programmer and web Architect. Currently working for http://www.talkspirit.com/

Updated on June 04, 2022

Comments

  • Brice Favre
    Brice Favre almost 2 years

    My table has an array indexed by a string, and i want all the records matching this string, no matter what the value is. For example get all the record wher id1 is fill :

    var a = {
       type: "Information",
       ids: {
         'id1' : '123'
         'id2' : '456'
       }
     };
    
    
    var b = {
       type: "Information",
       ids: {
         'id1' : '789'
       }
     };
    

    Is it possible to do that with mongodb and how?

  • Jeremy Haile
    Jeremy Haile over 11 years
    How do you create an index for this type of query?