Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

在 MongoDB 中串联字段 (Concatenate Fields) 使用 $concat

本文演示如何在 MongoDB Aggregation Pipeline 中使用 $concat 操作符将多个字符串字段连接成一个新字段。

创建示例数据

> db.concatenateFieldsDemo.insertOne({"StudentFirstName":"Adam","StudentLastName":"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd6ebf46d78f205348bc62e") }
> db.concatenateFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd6ebfc6d78f205348bc62f") }
> db.concatenateFieldsDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd6ec376d78f205348bc630") }
> db.concatenateFieldsDemo.insertOne({"StudentFirstName":"Sam","StudentLastName":"Williams"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd6ec436d78f205348bc631") }

显示原始数据

> db.concatenateFieldsDemo.find().pretty();
{ "_id" : ObjectId("5cd6ebf46d78f205348bc62e"), "StudentFirstName" : "Adam", "StudentLastName" : "Smith" }
{ "_id" : ObjectId("5cd6ebfc6d78f205348bc62f"), "StudentFirstName" : "John", "StudentLastName" : "Doe" }
{ "_id" : ObjectId("5cd6ec376d78f205348bc630"), "StudentFirstName" : "David", "StudentLastName" : "Miller" }
{ "_id" : ObjectId("5cd6ec436d78f205348bc631"), "StudentFirstName" : "Sam", "StudentLastName" : "Williams" }

使用 $concat 连接 FirstName 和 LastName(中间加 / 分隔符)

> db.concatenateFieldsDemo.aggregate([
  { $project: {
    "StudentFullName": { $concat: ["$StudentFirstName", "/", "$StudentLastName"] },
    "StudentFirstName": 1,
    "StudentLastName": 1
  }}
]);

结果

{ "_id" : ObjectId("5cd6ebf46d78f205348bc62e"), "StudentFirstName" : "Adam", "StudentLastName" : "Smith", "StudentFullName" : "Adam/Smith" }
{ "_id" : ObjectId("5cd6ebfc6d78f205348bc62f"), "StudentFirstName" : "John", "StudentLastName" : "Doe", "StudentFullName" : "John/Doe" }
{ "_id" : ObjectId("5cd6ec376d78f205348bc630"), "StudentFirstName" : "David", "StudentLastName" : "Miller", "StudentFullName" : "David/Miller" }
{ "_id" : ObjectId("5cd6ec436d78f205348bc631"), "StudentFirstName" : "Sam", "StudentLastName" : "Williams", "StudentFullName" : "Sam/Williams" }

$concat 语法说明

  • { $concat: [ <expression1>, <expression2>, ... ] }
  • 所有参数必须是字符串(或可转换为字符串)
  • 如果任一参数为 null/missing,结果为 null(除非用 $ifNull 处理)

处理可能为 Null 的字段

db.collection.aggregate([
  { $project: {
    fullName: {
      $concat: [
        { $ifNull: ["$firstName", ""] },
        " ",
        { $ifNull: ["$lastName", ""] }
      ]
    }
  }}
]);

其他字符串操作符

实际应用场景

  • 生成显示用的全名、地址拼接
  • 创建搜索用的组合字段(如 firstName + lastName + email)
  • 构建 URL、文件路径、唯一标识符
  • 报表中的格式化输出
Operator用途示例
$substr/$substrBytes/$substrCP截取子字符串{ $substr: ["$name", 0, 3] }
$toLower/$toUpper大小写转换{ $toUpper: "$name" }
$trim/$ltrim/$rtrim去除空白{ $trim: { input: "$name" } }
$split分割字符串为数组{ $split: ["$name", " "] }
$regexFind/$regexMatch正则匹配/查找{ $regexMatch: { input: "$email", regex: ".*@.*" } }