Mongodb:如何连接两个字段的字符串
您可以使用以下语法将两个字段中的字符串连接到 MongoDB 中的新字段中:
db.myCollection.aggregate([ { $project : { newfield: { $concat : [ " $field1 ", " - ", " $field2 " ] } } }, { $merge : "myCollection" } ])
此特定示例将字符串“field1”和“field2”连接成一个名为“newfield”的新字段,并将该新字段添加到名为myCollection的集合中。
以下示例展示了如何在具有以下文档的催收团队的实践中使用此语法:
db.teams.insertOne({team: " Mavs ", conference: " Western ", points: 31}) db.teams.insertOne({team: " Spurs ", conference: " Western ", points: 22}) db.teams.insertOne({team: " Rockets ", conference: " Western ", points: 19}) db.teams.insertOne({team: " Celtics ", conference: " Eastern ", points: 26}) db.teams.insertOne({team: " Cavs ", conference: " Eastern ", points: 33}) db.teams.insertOne({team: " Nets ", conference: " Eastern ", points: 38})
示例:在 MongoDB 中连接字符串
我们可以使用以下代码将“team”字段和“conference”字段中的字符串连接到一个名为“teamConf”的新字段中,并将该字段添加到team集合中:
db.teams.aggregate([ { $project : { teamConf: { $concat : [ " $team ", " - ", " $conference " ] } } }, { $merge : "teams" } ])
更新后的集合现在如下所示:
{ _id: ObjectId("62013d8c4cb04b772fd7a90c"), team: 'Mavs', conference: 'Western', points: 31, teamConf: 'Mavs - Western' } { _id: ObjectId("62013d8c4cb04b772fd7a90d"), team: 'Spurs', conference: 'Western', points: 22, teamConf: 'Spurs - Western' } { _id: ObjectId("62013d8c4cb04b772fd7a90e"), team: 'Rockets', conference: 'Western', points: 19, teamConf: 'Rockets - Western' } { _id: ObjectId("62013d8c4cb04b772fd7a90f"), team: 'Celtics', conference: 'Eastern', points: 26, teamConf: 'Celtics - Eastern' } { _id: ObjectId("62013d8c4cb04b772fd7a910"), team: 'Cavs', conference: 'Eastern', points: 33, teamConf: 'Cavs - Eastern' } { _id: ObjectId("62013d8c4cb04b772fd7a911"), team: 'Nets', conference: 'Eastern', points: 38, teamConf: 'Nets - Eastern' }
请注意,每个文档都有一个名为“teamConf”的新字段,其中包含“team”和“conference”字段的串联。
对于这个特定的示例,我们选择使用连字符作为分隔符来连接两个字符串。
但是,我们可以选择连接两个字符串,并且它们之间不使用任何分隔符值。
以下代码展示了如何执行此操作:
db.teams.aggregate([ { $project : { teamConf: { $concat : [ " $team ", " $conference " ] } } }, { $merge : "teams" } ])
更新后的集合如下所示:
{ _id: ObjectId("62013d8c4cb04b772fd7a90c"), team: 'Mavs', conference: 'Western', points: 31, teamConf: 'MavsWestern' } { _id: ObjectId("62013d8c4cb04b772fd7a90d"), team: 'Spurs', conference: 'Western', points: 22, teamConf: 'SpursWestern' } { _id: ObjectId("62013d8c4cb04b772fd7a90e"), team: 'Rockets', conference: 'Western', points: 19, teamConf: 'RocketWestern' } { _id: ObjectId("62013d8c4cb04b772fd7a90f"), team: 'Celtics', conference: 'Eastern', points: 26, teamConf: 'CelticsEastern' } { _id: ObjectId("62013d8c4cb04b772fd7a910"), team: 'Cavs', conference: 'Eastern', points: 33, teamConf: 'CavsEastern' } { _id: ObjectId("62013d8c4cb04b772fd7a911"), team: 'Nets', conference: 'Eastern', points: 38, teamConf: 'NetsEastern' }
请注意,标题为“teamConf”的新字段包含“team”和“conference”字段的串联,它们之间没有任何分隔值。
注意:您可以在此处找到$concat函数的完整文档。
其他资源
以下教程解释了如何在 MongoDB 中执行其他常见操作: