mongodbcouchdbcouchdb-mango

Couchdb Mango Query selector on object in array of objects


I have a couch db filled with entries in this form

{
  ...
  "templates" :[
    {"template_id":"1"}
    {"template_id":"2"}
    {"template_id":"3"}
  ]
}

I am trying to write a mango query that will find all entries that have templates that contains an object with a specific template_id. I know that it is possible with views but I want to use a mango query if possible


Solution

  • You should try the $elemMatch operator in Mango Query selector. This operator "returns all documents that contain an array field with at least one element matching the supplied query criteria"

    This selector will retrieve any document that contains template_id:1 in the templates array

      {
        "templates": {
          "$elemMatch": 
            {"template_id":"1"} 
        }
      }
    

    The elemMatch operator accepts a selector expression so you can write more complex queries.

     {
        "templates": {
          "$elemMatch": {"$or":[
            {"template_id":"1"},
            {"template_id":"3"}
            ]
          }
      }