本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$concat
Amazon DocumentDB 中的$concat聚合运算符连接(或组合)文档中的多个字符串,生成一个可以返回给应用程序的字符串。这减少了在应用程序中完成的工作,因为字符串操作是在数据库级别执行的。
参数
-
expression1: 要连接的第一个字符串。
-
expression2: 要连接的第二个字符串。
-
...:要连接的其他字符串(可选)。
示例(MongoDB 外壳)
在此示例中,我们将用户的名字和姓氏连接起来生成每个人的全名。
创建示例文档
db.people.insertMany([
{ "_id":1, "first_name":"Jane", "last_name":"Doe", "DOB":"2/1/1999", "Desk": "MSP102-MN"},
{ "_id":2, "first_name":"John", "last_name":"Doe", "DOB":"12/21/1992", "Desk": "DSM301-IA"},
{ "_id":3, "first_name":"Steve", "last_name":"Smith", "DOB":"3/21/1981", "Desk":"MKE233-WI"}
])
查询示例
db.people.aggregate([
{ $project: { full_name: { $concat: [ "$first_name", " ", "$last_name"] } } }
])
输出
{ "_id" : 1, "full_name" : "Jane Doe" }
{ "_id" : 2, "full_name" : "John Doe" }
{ "_id" : 3, "full_name" : "Steve Smith" }
代码示例
要查看使用该$concat命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function concatenateNames() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const result = await db.collection('people').aggregate([
{ $project: { full_name: { $concat: [ "$first_name", " ", "$last_name"] } } }
]).toArray();
console.log(result);
await client.close();
}
concatenateNames();
- Python
-
from pymongo import MongoClient
def concatenate_names():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client['test']
result = list(db.people.aggregate([
{ '$project': { 'full_name': { '$concat': [ '$first_name', ' ', '$last_name' ] } } }
]))
print(result)
client.close()
concatenate_names()