MongoDB $concat 运算符
$concat
运算符在 MongoDB 中是什么
MongoDB 提供了一系列字符串表达式操作符,用于聚合管道阶段。concat 运算符是其中一种运算符。concat 运算符用于将两个或多个字符串连接为一个字符串。
$concat
运算符的语法
{ $concat : [ < expression 1 >, < expression 2 >, ... ] }
这个运算符中传入的参数可以是任何有效的表达式,直至它解析为字符串。
- 如果参数的值引用了一个缺失的字段或null,$concat运算符将返回null。
示例
假设我们有一个学生的集合,其中包含以下文档。
>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运算符将名称字段与姓氏字段连接起来。
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运算符将姓名字段与姓氏字段连接起来。
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运算符将名字字段与姓氏连接起来。
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
}
另一个示例:
db.students.aggregate(
[
{ match : { _id : {nin: [ 4, 5, 6, 7 ] } } },
{ project : { _id : 1,
Student : {concat: [ "firstName", " ", "surname", ", ", "$department"] },
fees : 1
}
}
]
)
输出结果:
{
"_id" : 1,
"Student" : "Steve Smith, B-tech",
"fees" : 80000
}
{
"_id" : 2,
"Student" : "Sandy Beach, BCA",
"fees" : 55000
}
{
"_id" : 3,
"Student" : "John Cena, MCA",
"fees" : 85000
}