MongoDB $concat 运算符
MongoDB $concat 运算符 介绍
MongoDB 提供了多种用于聚合管道阶段的字符串表达式运算符。$concat 运算符就是这些运算符之一。$concat 运算符用于将两个或多个字符串连接成一个字符串。
MongoDB $concat 运算符 语法
{ $concat : [ < expression 1 >, < expression 2 >, ... ] }
在此运算符中传递的参数可以是任何有效的表达式,直到它解析为字符串。
- 如果参数的值引用了缺失的字段或 null,则 $concat 运算符返回 null。
MongoDB $concat 运算符 例子
假设我们有一组具有以下文档的学生。
>db.students.find().pretty()
{
{
"_id" : 1,
"name" : "Steve",
"surname" : "Smith",
"department" : "B-tech",
"fees" : 80000
}
{
"_id" : 2,
"name" : "Sandy",
"surname" : "Beach",
"department" : "BCA",
"fees" : 55000
}
{
"_id" : 3,
"name" : "John",
"surname" : "Cena",
"department" : "MCA",
"fees" : 85000
}
{
"_id" : 4,
"name" : "Wick",
"surname" : "John",
"department" : "B.com",
"fees" : 60000
}
{
"_id" : 5,
"name" : "David",
"surname" : "Silva",
"department" : "null",
"fees" : 80000
}
}
示例 1:使用 $concat 运算符
在这个例子中,我们将使用 $concat 操作符连接 name 字段和 surname 字段。
db.students.aggregate(
[
{ $project : {
_id : 1,
name : { $concat: [ "$firstName", "$surname" ] },
department : 1,
fees : 1
}
}
]
)
输出结果为:
{
"_id" : 1,
"name" : "SteveSmith",
"department" : "B-tech",
"fees" : 80000
}
{
"_id" : 2,
"name" : "SandyBeach",
"department" : "BCA",
"fees" : 55000
}
{
"_id" : 3,
"name" : "JohnCena",
"department" : "MCA",
"fees" : 85000
}
{
"_id" : 4,
"name" : "WickJohn",
"department" : "B.com",
"fees" : 60000
}
{
"_id" : 5,
"name" : "DavidSilva",
"department" : "null",
"fees" : 80000
}
假设我们将以下文档添加到我们的集合中:
{
"_id" : 6,
"name" : "null",
"surname" : "Thomas",
"department" : "M.com",
"fees" : 60000
}
{
"_id" : 7,
"name" : "David",
"surname" : "null",
"department" : "BCA",
"fees" : 60000
}
示例 2:Null值
在这个例子中,我们将使用 $concat 操作符连接 name 字段和 surname 字段。
db.students.aggregate(
[
{ $match : { _id : { $nin: [ 1, 2, 3, 4, 5 ] } } },
{ $project : {
_id : 1,
name : { $concat: [ "$firstName", "$surname" ] },
department : 1,
fees : 1
}
}
]
)
输出结果为:
{
"_id" : 6,
"name" : null,
"department" : "M.com",
"fees" : 60000
}
{
"_id" : 7,
"name" : null,
"department" : "BCA",
"fees" : 60000
}
示例 3:两个以上的字符串
在此示例中,我们将使用 $concat 运算符将 name 字段与 surname 连接起来。
db.students.aggregate(
[
{ $match : { _id : { $nin: [ 4, 5, 6, 7 ] } } },
{ $project : {
_id : 1,
name : { $concat: [ "$firstName", " ", "$surname" ] },
department : 1,
fees : 1
}
}
]
)
输出结果为:
{
"_id" : 1,
"name" : "Steve Smith",
"department" : "B-tech",
"fees" : 80000
}
{
"_id" : 2,
"name" : "Sandy Beach",
"department" : "BCA",
"fees" : 55000
}
{
"_id" : 3,
"name" : "John Cena",
"department" : "MCA",
"fees" : 85000
}
热门文章
优秀文章