Operators: $type

Selecting documents where the value of a field is of a specific BSON type.

🪶 The $type
  • operator is used to select documents where the value of a field is of a BSON specific.

    The BSONs accepted by MerlinDB are:

    type: string - number: 2;
    type: object - number: 3;
    type: array - number: 4;
    type: undefined - number: 6;
    type: boolean - number: 8;
    type: date - number: 9;
    type: symbol - number: 14;
    type: number - number: 16;

    Database: Client > model: Users

    Here we will simulate a database with the Users collection:
    1
  • COLLECTION:
  • Users > [
    2  
  • {
  • name:
  • "Chris Axxwell",
  • nick:
  • "Chris",
  • family:
  • 'Father'
  • }
  • ,
    3  
  • {
  • name:
  • "Chris Buckman",
  • nick:
  • "Chris",
  • family:
  • ["Father", "Mother"]
  • }
  • ,
    4  
  • {
  • name:
  • "Santiago Smith",
  • nick:
  • "Lollipop",
  • family:
  • null
  • }
  • ,
    5  
  • {
  • name:
  • "Justin Dacker",
  • nick:
  • "Justin",
  • family:
  • 3
  • }
  • ,
    6  
  • {
  • name:
  • "Chris Morgan",
  • nick:
  • "Mor",
  • family:
  • 'Mother'
  • }
  • ,
    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
  • //$type: <array|string|number>;
  • 9clientModel
  • .find(
  • {
  •   
    10  
  • family:
  • {
  • $type:
  • [ "string", 'array' ]
  • }
  • 11  
  • //or
  • 12  
  • family:
  • {
  • $type:
  • 'number'
  • }
  • 13  
  • //or
  • 14  
  • family:
  • {
  • $type:
  • ['number',
  • 2
  • ]
  • }
  • 15  
  • //or
  • 16  
  • family:
  • {
  • $type:
  • 16
  • }
  • 17
    18
  • }
  • )
  • .then(
  • e =>
  • {
  • 19   console
  • .log(
  • e
  • )
  • ;
    20  
  • //returns: Using first example
  • 21   [  
    22      
  • {
  • name:
  • "Chris Axxwell",
  • nick:
  • "Chris",
  • family:
  • 'Father'
  • }
  • ,
    23      
  • {
  • name:
  • "Chris Buckman",
  • nick:
  • "Chris",
  • family:
  • ["Father", "Mother"]
  • }
  • ,
    24      
  • {
  • name:
  • "Chris Morgan",
  • nick:
  • "Mor",
  • family:
  • 'Mother'
  • }
  • ,
    25      ...
    26   ]
    27
  • }
  • )