Baptiste Pernet
Baptiste Pernet

Reputation: 3384

Query and build indexes for a dictionary of objects

MongoDB version: 3.6

We have the following structure

{
  ...
  "aircraft": {
    "TAIL_1": {
      "registration": "TAIL_1",
      "wifi" true,
      ...
    },
    "TAIL_2": {
      "registration": "TAIL_2",
      "wifi" false
      ...
    }
    ...
  }
}
  1. How can I query to get all the document that have an aircraft with wifi set to true/false?
  2. How can I build an index to speed up this kind of query?

It looks like that if we were using an array instead, it would be easier, but I would like to know what I can do with an object like that. Thank you

Upvotes: 0

Views: 113

Answers (1)

ray
ray

Reputation: 15286

you can use $where:

db.getCollection(<collection name>).find({
    $where: function(){
        for(var key in obj.aircraft){
            if(obj.aircraft[key].wifi == true){
                return true
            }
        }
    }
}).forEach(result => {
    print(result) 
})

One thing to note is that $where do full table scan, which may have performance concern.

For indexing/future query, I think your idea of using an array is easier. Or you may want to flatten your document into 1 document per 'TAIL', which you can use $group to recover a similar structure to the original one in aggregation pipeline.

Upvotes: 1

Related Questions