MongoDBでは、$type 集計パイプライン演算子は、引数のBSONタイプを返します。
これを使用して、特定のフィールドのタイプを見つけることができます。
例
catsというコレクションがあるとします。 次のドキュメントで:
{
"_id" : ObjectId("60173c09c8eb4369cf6ad9e0"),
"name" : "Scratch",
"born" : ISODate("2021-01-03T23:30:15.123Z"),
"weight" : 30
} 次のコードを使用して、これらのフィールドのタイプを返すことができます。
db.cats.aggregate(
[
{
$project:
{
_id: { $type: "$_id" },
name: { $type: "$name" },
born: { $type: "$born" },
weight: { $type: "$weight" }
}
}
]
).pretty() 結果:
{
"_id" : "objectId",
"name" : "string",
"born" : "date",
"weight" : "double"
} 例2
さまざまなBSONタイプのさまざまなフィールドを含む別の例を次に示します。
typesというコレクションがあります 次のドキュメントで:
{
"_id" : ObjectId("601738d7c8eb4369cf6ad9de"),
"double" : 123.75,
"string" : "123",
"boolean" : true,
"date" : ISODate("2020-12-31T23:30:15.123Z"),
"integer" : 123,
"long" : NumberLong(123),
"decimal" : NumberDecimal("123.75"),
"object" : {
"a" : 1
},
"array" : [
1,
2,
3
]
} この記事では、BSONタイプを反映するように各フィールドに名前を付けました。
これで、次のコードを使用して、これらのフィールドのタイプを返すことができます。
db.types.aggregate(
[
{
$project:
{
_id: { $type: "$_id" },
double: { $type: "$double" },
string: { $type: "$string" },
boolean: { $type: "$boolean" },
date: { $type: "$date" },
integer: { $type: "$integer" },
long: { $type: "$long" },
decimal: { $type: "$decimal" },
object: { $type: "$object" },
array: { $type: "$array" }
}
}
]
).pretty() 結果:
{
"_id" : "objectId",
"double" : "double",
"string" : "string",
"boolean" : "bool",
"date" : "date",
"integer" : "int",
"long" : "long",
"decimal" : "decimal",
"object" : "object",
"array" : "array"
} タイプによるフィルタリング
$typeもあります BSONタイプに基づいてドキュメントのコレクションをフィルタリングできる要素クエリ演算子。
番号を確認する
値が数値かどうかを確認したいだけの場合は、MongoDB $isNumberを参照してください。 。