Operators: $size

Selecting documents where the array field has a specific number of elements.

🪶 The $size operator is used to select documents where the array field has a specific number of elements.


Database: Client > model: Users

Here we will simulate a database with the Users collection:
1
  • COLLECTION:
  • Users > [
    2  
  • {
  • name:
  • "Chris Axxwell",
  • pets:
  • ['cat', 'dog', 'shark']  
  • }
  • ,
    3  
  • {
  • name:
  • "Chris Buckman",  
  • pets:
  • ['cat', 'bird', 'monkey']
  • }
  • ,
    4  
  • {
  • name:
  • "Santiago Smith",  
  • pets:
  • ['cat']
  • }
  • ,
    5  
  • {
  • name:
  • "Justin Dacker",  
  • pets:
  • ['cat', 'dog' ]
  • }
  • ,
    6  
  • {
  • name:
  • "Chris Morgan",  
  • pets:
  • ['cat' ]
  • }
  • ,
    7   ...
    8]

    Query the above database:

    1
  • import
  • MerlinDB,
  • {
  • Schema
  • }
  • from
  • "@chrisaxxwell/merlin-db";
    2
  • //Or if you are using 'merlindb.max.js' just call 'new MerlinDB()';
  • 3
    4
  • const
  • merlin =
  • new
  • MerlinDB(
  • )
  • ;
    5merlin
  • .connect(
  • "Client"
  • )
  • ;
    6
  • var
  • clientModel = merlin
  • .model(
  • "Users", <userSchema>
  • )
  • ;
    7
    8
  • //$size: <number>;
  • 9clientModel
  • .find(
  • {
  • 10  
  • pets:
  • {
  • $size:
  • 3
  • }
  • 11
  • }
  • )
  • .then(
  • e =>
  • {
  • 12   console
  • .log(
  • e
  • )
  • ;
    13  
  • //returns:
  • 14   [
    15      
  • {
  • name:
  • "Chris Axxwell",
  • pets:
  • ['cat', 'dog', 'shark']  
  • }
  • ,
    16      
  • {
  • name:
  • "Chris Buckman",  
  • pets:
  • ['cat', 'bird', 'monkey']
  • }
  • ,
    17      ...
    18   ]
    19
  • }
  • )