要连接字段,请使用$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") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> 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" }
以下是选择和连接字段的查询-
> 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" }