MongoDB $cmp 运算符
MongoDB $cmp 运算符 介绍
MongoDB 提供了多种聚合管道操作符。$cmp 运算符就是这些运算符之一。$cmp 运算符用于比较两个值或类型并返回结果。
它根据这些条件返回以下结果:
- 如果两个值相等,则返回 0。
- 如果第一个值大于第二个值,则返回 1。
- 如果第一个值小于第二个值,则返回 -1。
MongoDB $cmp 运算符 语法
{ $cmp : [ < expression 1 >, < expression 2 > ] }
MongoDB $cmp 运算符 例子
假设我们有一个包含以下文档的产品集合。
{
{
"_id" : 1,
"name" : "rectangle",
"length" : 11,
"breath" : 10
}
{
"_id" : 2,
"name" : "square",
"length" : 10,
"breath" : 10
}
{
"_id" : 3,
"name" : "rectangle",
"length" : 14,
"breath" : 16
}
{
"_id" : 4,
"name" : "square",
"length" : 6,
"breath" : 6
}
{
"_id" : 5,
"name" : "rectangle",
"length" : 11,
"breath" : 16
}
}
示例 1:使用 $cmp 运算符
在此示例中,我们将使用 $cmp 运算符比较长度和宽度字段。
db.products.aggregate (
[
{ $project :
{
_id : 1,
name : 1,
length : 1,
breadth : 1,
result: { $cmp : [ "$length", "$breadth" ] }
}
}
]
)
输出结果为:
{
"_id" : 1,
"name" : "rectangle",
"length" : 11,
"breath" : 10,
"result" : 1
}
{
"_id" : 2,
"name" : "square",
"length" : 10,
"breath" : 10,
"result" : 0
}
{
"_id" : 3,
"name" : "rectangle",
"length" : 14,
"breath" : 16,
"result" : -1
}
{
"_id" : 4,
"name" : "square",
"length" : 6,
"breath" : 6,
"result" : 0
}
{
"_id" : 5,
"name" : "rectangle",
"length" : 11,
"breath" : 16,
"result" : -1
}
假设我们将以下文档添加到我们的集合中:
{
{
"_id" : 6,
"name" : "rectangle",
"length" : null,
"breath" : 10
}
{
"_id" : 7,
"name" : "square",
"length" : 10,
"breath" : null
}
{
"_id" : 8,
"name" : "rectangle",
"length" : null,
"breath" : null
}
}
示例 2:比较NULL值
db.products.aggregate (
[
{ $match : {_id : { $nin : [ 1, 2, 3, 4, 5 ] } } },
{ $project :
{
_id : 1,
name : 1,
length : 1,
breadth : 1,
result: { $cmp : [ "$length", "$breadth" ] }
}
}
]
)
输出结果为:
{
"_id" : 6,
"name" : "rectangle",
"length" : null,
"breath" : 10,
"result" : -1
}
{
"_id" : 7,
"name" : "square",
"length" : 10,
"breath" : null,
"result" : 1
}
{
"_id" : 8,
"name" : "rectangle",
"length" : null,
"breath" : null,
"result" : 0
}
假设我们将以下文档添加到我们的集合中:
{
"_id" : 9,
"name" : "item_1",
"a" : ISODate("2020-05-09T23:30:15.100Z"),
"b" : 10
}
{
"_id" : 10,
"name" : "item_2",
"a" : 10,
"b" : ISODate("2012-11-18T04:00:20.112Z")
}
{
"_id" : 11,
"name" : "item_3",
"a" : ISODate("2018-11-14T04:00:20.112Z"),
"b" : ISODate("2015-10-07T04:00:20.112Z")
}
示例 3:比较不同类型
db.products.aggregate (
[
{ $match : {_id : { $nin : [ 1, 2, 3, 4, 5, 6, 7, 8 ] } } },
{ $project :
{
_id : 1,
name : 1,
a : 1,
b : 1,
result: { $cmp : [ "$a", "$b" ] }
}
}
]
)
输出结果为:
{
"_id" : 9,
"name" : "item_1",
"a" : ISODate("2020-05-09T23:30:15.100Z"),
"b" : 10,
"result" : 1
}
{
"_id" : 10,
"name" : "item_2",
"a" : 10,
"b" : ISODate("2012-11-18T04:00:20.112Z"),
"result" : -1
}
{
"_id" : 11,
"name" : "item_3",
"a" : ISODate("2018-11-14T04:00:20.112Z"),
"b" : ISODate("2015-10-07T04:00:20.112Z"),
"result" : 1
}
热门文章
优秀文章