Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoDB concatenate results

Tags:

mongodb

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.

like image 817
Castles Avatar asked Feb 25 '23 21:02

Castles


2 Answers

In the PHP Driver

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.)

In the Shell

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"
}
like image 132
Charles Hooper Avatar answered Mar 05 '23 17:03

Charles Hooper


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" ] } } }
   ]
)
like image 41
rebe100x Avatar answered Mar 05 '23 16:03

rebe100x