$all in MongoDB

author image
$all Operator Description

- Matches arrays that contain all the specified values in the query condition.

The $size operator matches any array with the number of elements specified by the argument. Purpose: to get the documents from a specific collection by using the length of an array.

Question?

To display an elements returns the documents with 2 elements in the name array.

   
  
  

db.getCollection("author").find( { tags: { $all: [ "fun", "laugh"] } } )
{
  "_id" : ObjectId("6381e08e9bde0b0f52d37f3a"),
  "title" : "1 title",
  "author" : "bob",
  "posted" : ISODate("2022-11-26T09:46:54.504+0000"),
  "pageViews" : 5.0,
  "tags" : [
      "fun",
      "good",
      "fun"
  ],
  "comments" : [
      {
          "author" : "joe",
          "text" : "this is cool"
      },
      {
          "author" : "sam",
          "text" : "this is bad"
      }
  ],
  "other" : {
      "foo" : 5.0
  }
}
{
  "_id" : ObjectId("6381e09c9bde0b0f52d37f3b"),
  "title" : "title2",
  "author" : "bob",
  "posted" : ISODate("2022-11-26T09:47:08.798+0000"),
  "pageViews" : 5.0,
  "tags" : [
      "fun",
      "good",
      "fun"
  ],
  "comments" : [
      {
          "author" : "joe",
          "text" : "this is cool"
      },
      {
          "author" : "sahir",
          "text" : "this is bad"
      }
  ],
  "other" : {
      "foo" : 5.0
  }
}
    
Query:
   
  
    db.getCollection("author").find( { tags: { $all: [ "fun", "laugh"] } } 
     
        
        
Another Example. Earlier version or mongodb versions 2.2+ Query:
   
        
               {
     db.collection.find( { $where: "this.name.length > 1" } );
              
              
        
Query:
  
     
     
  db.collection.find({
  shapes: {
    "$elemMatch": {
      color: "red"
    }
  }
},
{
  "shapes.color": 1
})
              
                   

Comments