Whats the best way to concatenate results in MongoDB? In particular the PHP driver? Do I need to use mapReduce?
In mySQL I would do something like this: SELECT CONCAT(fname,' ',lname) as name FROM users but I can't seem to find a simple way to do this in mongo.
I recommend doing this in your application. Use PHP's concatenation features to add a "fullname" attribute/key to the user object/array. I'd stay away from map/reduce/finalize unless you need to do some database-side processing or selecting before returning the results. (And, before that, maybe look into where
queries as well - http://www.mongodb.org/display/DOCS/Advanced+Queries.)
If this is a one-off query and you're doing it in the shell, there are two different (but related) ways to go about this.
Which one you use depends widely on if only want the concat-ed name or if you want the rest of the document to go with it. For instance, if you only want the name, you can do something like this:
> db.show_concat.find().forEach( function (o) { print(o.fname + ' ' + o.lname); } )
john smith
jane doe
Otherwise, if you want the other fields, you can do:
> db.show_concat.find().forEach( function (o) { o.full_name = o.fname + ' ' + o.lname; printjson(o); } )
{
"_id" : ObjectId("4cd6dabb5391d08d405bb0bb"),
"fname" : "john",
"lname" : "smith",
"full_name" : "john smith"
}
{
"_id" : ObjectId("4cd6daee5391d08d405bb0bc"),
"fname" : "jane",
"lname" : "doe",
"full_name" : "jane doe"
}
You can use aggregate, $project and $concat : https://docs.mongodb.org/v3.0/reference/operator/aggregation/project/ https://docs.mongodb.org/manual/reference/operator/aggregation/concat/
It would be something like this :
db.show_concat.aggregate(
[
{ $project: { full_name: { $concat: [ "$fname", " - ", "$lname" ] } } }
]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With