$type

L'operatore $type recupera i documenti se un campo scelto è del tipo specificato. L'operatore $type è utile per la convalida dei dati e per garantire la coerenza tra i documenti in una raccolta.

Sintassi

{
  <field>: { $type: <BSON type number> | <string alias> }
}

Parametri

Parametro Description
field Campo di cui controllare il tipo.
BSON type number Numero corrispondente al tipo BSON, ad esempio 1 per double, 2 per string.
string alias Alias stringa per il tipo BSON, ad esempio "double", "string", "object", "array".

Tipi BSON comuni

TIPO Number Alias Description
Double 1 "double" Virgola mobile a 64 bit
String 2 "string" Stringa UTF-8
Oggetto 3 "object" Documento incorporato
Array 4 "array" Array
ObjectId 7 "objectId" ObjectId
Boolean 8 "bool" Boolean
Date 9 "date" Date
Null 10 "null" Valore Null
Intero a 32 bit 16 "int" Intero a 32 bit
Marca temporale: 17 "timestamp" Marca temporale:
Intero a 64 bit 18 "long" Intero a 64 bit

Esempi

Si consideri questo documento di esempio dalla raccolta negozi.

{
    "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
    "name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
    "location": {
        "lat": -89.2384,
        "lon": -46.4012
    },
    "staff": {
        "totalStaff": {
            "fullTime": 8,
            "partTime": 20
        }
    },
    "sales": {
        "totalSales": 75670,
        "salesByCategory": [
            {
                "categoryName": "Wine Accessories",
                "totalSales": 34440
            },
            {
                "categoryName": "Bitters",
                "totalSales": 39496
            },
            {
                "categoryName": "Rum",
                "totalSales": 1734
            }
        ]
    },
    "promotionEvents": [
        {
            "eventName": "Unbeatable Bargain Bash",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 6,
                    "Day": 23
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 7,
                    "Day": 2
                }
            },
            "discounts": [
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 7
                },
                {
                    "categoryName": "Bitters",
                    "discountPercentage": 15
                },
                {
                    "categoryName": "Brandy",
                    "discountPercentage": 8
                },
                {
                    "categoryName": "Sports Drinks",
                    "discountPercentage": 22
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 19
                }
            ]
        },
        {
            "eventName": "Steal of a Deal Days",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 21
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 29
                }
            },
            "discounts": [
                {
                    "categoryName": "Organic Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "White Wine",
                    "discountPercentage": 20
                },
                {
                    "categoryName": "Sparkling Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 17
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 23
                }
            ]
        }
    ]
}

Esempio 1: Trovare archivi con nomi di tipo string

Per trovare qualsiasi negozio il cui nome è di tipo stringa, eseguire una query usando l'operatore $type nel campo nome. Proiettare quindi solo i campi ID e nome e limitare i risultati a un documento dal set di risultati.

db.stores.find({
    "name": {
        $type: "string"
    }
}, {
    "_id": 1,
    "name": 1
}).limit(1)

Questa query restituisce il risultato seguente:

[
    {
        "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6",
        "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort"
    }
]

Esempio 2: Convalida dei dati con più controlli del tipo

Questa query illustra come verificare che i campi essenziali nella struttura del documento della raccolta abbiano i tipi di dati desiderati.

db.stores.find({
      "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
      "name": {
          $type: "string"
      },
      "location": {
          $type: "object"
      },
      "staff.employeeCount.fullTime": {
          $type: ["int", "long"]
      },
      "promotionEvents": {
          $type: "array"
      }
  }, {
      "_id": 1,
      "name": 1,
      "location": 1,
      "staff": 1
  }
)

Questa query restituisce il risultato seguente.

[
    {
        "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
        "name": "Trey Research | Home Office Depot - Lake Freeda",
        "location": {
            "lat": -48.9752,
            "lon": -141.6816
        },
        "staff": {
            "employeeCount": {
                "fullTime": 12
            }
        }
    }
]