In the mongodb query statement, the user can query the document data that matches the field type by specifying the $type value. In mongodb aggregation operations, the $type operator also exists. This article introduces $type in aggregation operations.
definition
Returns a string representing the BSON type of the passed parameter. In aggregation operations, follow the following syntax to return type information
{$type: <expression>}
Among them, expression can be any legal expression such as field name, operation, etc.
Behavior
Different from $type usage in query filters. $type in aggregation operations is used to return the result type in the expression. If an array is passed in as a parameter, the array type is returned.
When a field name is specified as an argument, $type returns the string "missing" when the field does not exist in the document.
The following table describes the results obtained when different parameters are passed in.
expression |
result |
{$type: "a"} |
"string" |
{$type: /a/} |
"regex" |
{$type: 1} |
"double" |
{$type: NumberLong(627)} |
"long" |
{$type: {x: 1}} |
"object" |
{$type: [ [1, 2, 3] ]} |
"array" |
Among them, in order to prevent the array [1, 2, 3] from being parsed into a parameter list, the array is converted into a literal meaning.
application
There are the following 6 documents in the collection coll.
db.coll.insertMany([
{_id: 0, a: 8},
{_id: 1, a: [ 41.63, 88.19]},
{_id: 2, a: {a: "apple", b: "banana", c: "carrot"}},
{_id: 3, a: "caribou"},
{_id: 4, a: NumberLong(71)},
{_id: 5},
])
Use aggregate query to query the type of field a
db.coll.aggregate([{
$project: {
a: {$type: "$a"}
}
}])
/* 1 */
{
"_id" : 0,
"a" : "int"
},
/* 2 */
{
"_id" : 1,
"a" : "array"
},
/* 3 */
{
"_id" : 2,
"a" : "object"
},
/* 4 */
{
"_id" : 3,
"a" : "string"
},
/* 5 */
{
"_id" : 4,
"a" : "long"
},
/* 6 */
{
"_id" : 5,
"a" : "missing"
}
Let’s try the type of array returned in the example above. When passing in the array directly, mongodb returned an error. Mongodb parses the directly passed array into 3 parameters. $type can only accept one parameter
//直接传入一个数组
db.coll.aggregate([{
$project: {
a: {$type: [1,2,3]}
}
}])
{
"message" : "Invalid $project :: caused by :: Expression $type takes exactly 1 arguments. 3 were passed in.",
"ok" : 0,
"code" : 16020,
"codeName" : "Location16020"
}
Therefore we need to pass the literal meaning of the array as an expression to $type as a parameter.
db.coll.aggregate([{
$project: {
a: {$type: {$literal: [1,2,3]}} //使用$literal传递数组的字面意义,不要被解析
}
}])
Or pass the entire array as a parameter to $type
db.coll.aggregate([{
$project: {
a: {$type: [[1,2,3]]}
}
}])
Here, $type is followed by an array, and only one element in the array is an array of [1,2,3]. When mongodb parses, it gets this array as a parameter.