Learn the "why" behind slow queries and how to fix them in our 2-Part Webinar.
Register now >
Menu Docs
Página inicial do Docs
/ /

$type (operador de predicado da query)

$type

$type selects documents where the value of the field is an instance of the specified BSON type(s). Querying by data type is useful for unstructured data where data types aren't predictable.

Você pode utilizar o $type para implantações hospedadas nos seguintes ambientes:

  • MongoDB Atlas: o serviço totalmente gerenciado para implantações do MongoDB na nuvem

  • MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB

  • MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB

Uma expressão $type para um único tipo de BSON tem a seguinte sintaxe:

{ field: { $type: <BSON type> } }

Você pode especificar o número ou o apelido do tipo BSON.

A expressão $type também pode aceitar um array de tipos de BSON e tem a seguinte sintaxe:

{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }

A query acima corresponde a documentos em que o valor field é qualquer um dos tipos listados. Os tipos especificados no array podem ser apelidos numéricos ou de string.

For an example, see Querying by Multiple Data Types.

Tipos disponíveis descreve os tipos de BSON e seus apelidos numéricos e de string correspondentes.

Dica

$type retorna documentos em que o tipo de BSON do field corresponde ao tipo de BSON passado para $type.

Para documentos em que field é uma array, $type retorna documentos nos quais pelo menos um elemento de array corresponde a um tipo passado para $type.

Queries de $type: "array" retornam documentos onde o próprio campo é uma array.

O operador $type aceita apelidos de string para os tipos de BSON, além dos números correspondentes aos tipos de BSON.

$type suporta o alias number, que corresponde aos seguintes tipos de BSON:

Por exemplo, consulte Exemplos.

MinKey and MaxKey are used in comparison operations and exist primarily for internal use. For all possible BSON element values, MinKey is always the smallest value, and MaxKey is always the greatest value.

Consultar minKey ou maxKey com $type retorna apenas campos que correspondem aos valores especiais MinKey ou MaxKey.

For example, the following data collection has these documents with MinKey and MaxKey:

db.data.insertMany( [
{ _id : 1, x : { "$minKey" : 1 } },
{ _id : 2, y : { "$maxKey" : 1 } }
] )

A query abaixo retorna o documento com _id: 1:

db.data.find( { x: { $type: "minKey" } } )

A query abaixo retorna o documento com _id: 2:

db.data.find( { y: { $type: "maxKey" } } )

The addressBook contains addresses and ZIP codes, where zipCode has string, int, double, and long values:

db.addressBook.insertMany( [
{ _id : 1, address : "2030 Martian Way", zipCode : "90698345" },
{ _id : 2, address : "156 Lunar Place", zipCode : 43339374 },
{ _id : 3, address : "2324 Pluto Place", zipCode : Long(3921412) },
{ _id : 4, address : "55 Saturn Ring" , zipCode : Int32(88602117) },
{ _id : 5, address : "104 Venus Drive", zipCode : ["834847278", "1893289032"] }
] )

The following queries return documents where zipCode is the BSON type string or is an array with an element of the specified type:

db.addressBook.find( { zipCode : { $type : 2 } } );
db.addressBook.find( { zipCode : { $type : "string" } } );

The queries return:

{ _id : 1, address : "2030 Martian Way", zipCode : "90698345" }
{ _id : 5, address : "104 Venus Drive", zipCode : [ "834847278", "1893289032" ] }

The following queries return documents where zipCode is the BSON type double or is an array with an element of the specified type:

db.addressBook.find( { zipCode : { $type : 1 } } );
db.addressBook.find( { zipCode : { $type : "double" } } );

Essas queries retornam:

{ _id : 2, address : "156 Lunar Place", zipCode : 43339374 }

The following query uses the number alias to return documents where zipCode is the BSON type double, int, or long or is an array with an element of the specified type:

db.addressBook.find( { zipCode : { $type : "number" } } )

Essas queries retornam:

{ _id : 2, address : "156 Lunar Place", zipCode : 43339374 }
{ _id : 3, address : "2324 Pluto Place", zipCode : Long(3921412) }
{ _id : 4, address : "55 Saturn Ring", zipCode : 88602117 }

A collection grades contém nomes e médias, onde classAverage tem valores string, int e double:

db.grades.insertMany( [
{ _id : 1, name : "Alice King" , classAverage : 87.333333333333333 },
{ _id : 2, name : "Bob Jenkins", classAverage : "83.52" },
{ _id : 3, name : "Cathy Hart", classAverage: "94.06" },
{ _id : 4, name : "Drew Williams" , classAverage : Int32("93") }
] )

The following queries return documents where classAverage is the BSON type string or double or is an array with an element of the specified type. The first query uses numeric aliases and the second query uses string aliases.

db.grades.find( { classAverage : { $type : [ 2 , 1 ] } } );
db.grades.find( { classAverage : { $type : [ "string" , "double" ] } } );

Essas queries retornam:

{ _id : 1, name : "Alice King", classAverage : 87.33333333333333 }
{ _id : 2, name : "Bob Jenkins", classAverage : "83.52" }
{ _id : 3, name : "Cathy Hart", classAverage : "94.06" }

A collection restaurants usa minKey para qualquer nota que seja reprovada:

db.restaurants.insertOne( [
{
_id: 1,
address: {
building: "230",
coord: [ -73.996089, 40.675018 ],
street: "Huntington St",
zipcode: "11231"
},
borough: "Brooklyn",
cuisine: "Bakery",
grades: [
{ date : new Date(1393804800000), grade : "C", score : 15 },
{ date : new Date(1378857600000), grade : "C", score : 16 },
{ date : new Date(1358985600000), grade : MinKey(), score : 30 },
{ date : new Date(1322006400000), grade : "C", score : 15 }
],
name : "Dirty Dan's Donuts",
restaurant_id : "30075445"
}
] )

E maxKey para qualquer nota que seja a nota mais alta para passar:

db.restaurants.insertOne( [
{
_id : 2,
address : {
building : "1166",
coord : [ -73.955184, 40.738589 ],
street : "Manhattan Ave",
zipcode : "11222"
},
borough: "Brooklyn",
cuisine: "Bakery",
grades: [
{ date : new Date(1393804800000), grade : MaxKey(), score : 2 },
{ date : new Date(1378857600000), grade : "B", score : 6 },
{ date : new Date(1358985600000), grade : MaxKey(), score : 3 },
{ date : new Date(1322006400000), grade : "B", score : 5 }
],
name : "Dainty Daisey's Donuts",
restaurant_id : "30075449"
}
] )

A seguinte query retorna qualquer restaurante cujo campo grades.grade contém minKey ou é uma array contendo um elemento do tipo especificado:

db.restaurants.find(
{ "grades.grade" : { $type : "minKey" } }
)

Isso retorna os seguintes resultados:

{
_id : 1,
address : {
building : "230",
coord : [ -73.996089, 40.675018 ],
street : "Huntington St",
zipcode : "11231"
},
borough : "Brooklyn",
cuisine : "Bakery",
grades : [
{ date : ISODate("2014-03-03T00:00:00Z"), grade : "C", score : 15 },
{ date : ISODate("2013-09-11T00:00:00Z"), grade : "C", score : 16 },
{ date : ISODate("2013-01-24T00:00:00Z"), grade : { "$minKey" : 1 }, score : 30 },
{ date : ISODate("2011-11-23T00:00:00Z"), grade : "C", score : 15 }
],
name : "Dirty Dan's Donuts",
restaurant_id : "30075445"
}

A seguinte query retorna qualquer restaurante cujo campo grades.grade contém maxKey ou é uma array contendo um elemento do tipo especificado:

db.restaurants.find(
{ "grades.grade" : { $type : "maxKey" } }
)

Isso retorna os seguintes resultados:

{
_id : 2,
address : {
building : "1166",
coord : [ -73.955184, 40.738589 ],
street : "Manhattan Ave",
zipcode : "11222"
},
borough : "Brooklyn",
cuisine : "Bakery",
grades : [
{ date : ISODate("2014-03-03T00:00:00Z"), grade : { "$maxKey" : 1 }, score : 2 },
{ date : ISODate("2013-09-11T00:00:00Z"), grade : "B", score : 6 },
{ date : ISODate("2013-01-24T00:00:00Z"), grade : { "$maxKey" : 1 }, score : 3 },
{ date : ISODate("2011-11-23T00:00:00Z"), grade : "B", score : 5 }
],
name : "Dainty Daisey's Donuts",
restaurant_id : "30075449"
}

Uma coleção chamada sensorReading contém os seguintes documentos:

db.sensorReading.insertMany( [
{ _id : 1, readings : [ 25, 23, [ "Warn: High Temp!", 55 ], [ "ERROR: SYSTEM SHUTDOWN!", 66 ] ] },
{ _id : 2, readings : [ 25, 25, 24, 23 ] },
{ _id : 3, readings : [ 22, 24, [] ] },
{ _id : 4, readings : [] },
{ _id : 5, readings : 24 }
] )

The following query returns any document where the readings field is an array:

db.sensorReading.find( { readings : { $type: "array" } } )

A consulta retorna os seguintes documentos:

{
_id : 1,
readings : [
25,
23,
[ "Warn: High Temp!", 55 ],
[ "ERROR: SYSTEM SHUTDOWN!", 66 ]
]
},
{
_id : 2,
readings : [ 25, 25, 24, 23 ]
},
{
_id : 3,
readings : [ 22, 24, [] ]
},
{
_id : 4,
readings : []
}

Nos documentos com _id : 1, _id : 2, _id : 3 e _id : 4, o campo readings é uma array.

Voltar

$exists

Nesta página