Mongodb聚合操作中的$type

在mongodb查询语句中,用户可以通过指定$type值,查询出的符合字段类型的文档数据。在mongodb聚合操作中,也存在$type操作符。本文就聚合操作中的$type进行介绍。

定义

返回一个表示传入参数BSON类型的字符串。在聚合操作中,按照下面的语法来返回类型信息

{$type: <expression>}

其中,expression可以是字段名称,运算等任何合法的表达式。

行为

与查询过滤器中的$type用法不同。聚合操作中的$type用来返回表达式中的结果类型。如当传入一个数组作为参数是,返回数组类型。

当指定字段名称作为参数时,当文档中不存在该字段时,$type返回字符串"missing"。

下面表格描述了传入不同参数时获取到的结果。

表达式

结果

{$type: "a"}

"string"

{$type: /a/}

"regex"

{$type: 1}

"double"

{$type: NumberLong(627)}

"long"

{$type: {x: 1}}

"object"

{$type: [ [1, 2, 3] ]}

"array"

其中,为了避免数组[1, 2, 3]被解析成参数列表,这里将数组转换成了字面意义。

应用

在集合coll中有下面6个文档。

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},
    ])

使用聚合查询,查询字段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"
}

再来试试上面举例中返回数组的类型。直接传入数组时, mongodb返回了一个错误。 mongodb把直接传入的数组解析成了3个参数。而$type只能接受一个参数

//直接传入一个数组
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"
}

因此我们需要将数组的字面意义作为表达式传递给$type作为参数。

db.coll.aggregate([{
    $project: {
        a: {$type: {$literal: [1,2,3]}} //使用$literal传递数组的字面意义,不要被解析
    }
}])

或者把数组整体作为一个参数,传递给$type

db.coll.aggregate([{
    $project: {
        a: {$type: [[1,2,3]]}
    }
}])

这里, $type后面是一个数组,数组中只有一个元素是[1,2,3]的数组。当mongodb解析时,得到这个数组作为参数。

猜你喜欢

转载自blog.csdn.net/wilsonzane/article/details/135245180