$ concat mongodb中的两个字段 [英] $concat two fields in mongodb
本文介绍了$ concat mongodb中的两个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这两个收藏夹:
employees : {_id: NumberInt(0), name:"Max",surname:"Power"}, ..
和
loggableUser:{_id: NumberInt(0), employee: NumberInt(1), ..},
现在,我必须在以下查询中插入包含"employee.name" +"和"employee.surname"的"fullName"字段.我尝试了以下查询:
Now I have to insert into the following query a field "fullName" containing "employee.name" + " " + "employee.surname". I tried this query:
db.loggableUser.aggregate([
{
'$lookup':
{
'from': 'employees',
'localField': 'employee',
'foreignField' : '_id',
'as': 'employee'
}
},
{ "$addFields":{
"$employee.fullName" : "$employee.name" + " " + "$employee.surname"}])
但是它不起作用.我知道这是一件简单的事情,但我无法使它正常工作.谢谢.
but it does not work. I know is a simple thing but I can't get it works. Thank you.
推荐答案
您需要先 $ concat
组合两个字段.
You need to first $unwind
the employee
then you can use $concat
to combine two fields.
db.loggableUser.aggregate([
{ '$lookup': {
'from': 'employees',
'localField': 'employee',
'foreignField' : '_id',
'as': 'employee'
}},
{ '$unwind': '$employee' },
{ '$addFields': {
'employee.fullName' : { '$concat': ['$employee.name' + ' ' + '$employee.surname'] }
}}
])
Which is far easier with the mongodb 3.6 and above $lookup
syntax.
db.loggableUser.aggregate([
{ '$lookup': {
'from': 'employees',
'let': { 'employee': '$employee' },
'pipeline': [
{ '$match': { '$expr': { '$eq': ['$_id', '$$employee'] }}},
{ '$addFields': { 'fullName' : { '$concat': ['$name', ' ', '$surname'] }}}
]
'as': 'employee'
}}
])
这篇关于$ concat mongodb中的两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文