$elementmatch in mongodb

author image
$elemMatch in mongodb

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

You cannot specify a $where expression in an $elemMatch You cannot specify a $text query expression in an $elemMatch.

Question?

Now I want to display an elements in values that first element of them are "a" in array.

   
  
  
  {
  "values": 
    [
      ["a","231"],
      ["b","232"],
      ["c","233"],
      ["a","235"]  
    ]
}
    
Query:
   
  
  
    db.collection.find(
    {},
    {
        'values': {
            $elemMatch: {
                $elemMatch: {
                    $in: ['a']
                }
            }
        }
    }
)
     
        
Another Example. Here i want to get a red color shapesfrom a document.But it returns all documents if matches atleast one red in a collection. Query:
   
        
               {
    "_id": ObjectId("562e7c594c12942f08fe4192"),
    "shapes": [
      {
        "shape": "square",
        "color": "blue"
      },
      {
        "shape": "circle",
        "color": "red"
      }
    ]
  },
  {
    "_id": ObjectId("562e7c594c12942f08fe4193"),
    "shapes": [
      {
        "shape": "square",
        "color": "black"
      },
      {
        "shape": "circle",
        "color": "red"
      }
    ]
  }
              
              
        
Query:
   
  db.collection.find({
  shapes: {
    "$elemMatch": {
      color: "red"
    }
  }
},
{
  "shapes.color": 1
})
              
                   

Comments