mongoDB连接结果 [英] mongoDB concatenate results

查看:65
本文介绍了mongoDB连接结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中连接结果的最佳方法是什么?特别是PHP驱动程序?我需要使用mapReduce吗?

Whats the best way to concatenate results in MongoDB? In particular the PHP driver? Do I need to use mapReduce?

在mySQL中,我将执行以下操作:从用户名中选择CONCAT(fname,'',lname)作为名称,但我似乎找不到在mongo中执行此操作的简单方法.

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.

推荐答案

在PHP驱动程序中

我建议在您的应用程序中执行此操作.使用PHP的串联功能可以向用户对象/数组添加全名"属性/键.除非需要在返回结果之前进行一些数据库方面的处理或选择,否则我将远离map/reduce/finalize. (而且,在此之前,也许还要研究where查询- http://www .mongodb.org/display/DOCS/Advanced + Queries .)

如果这是一个一次性查询,而您是在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"
}

这篇关于mongoDB连接结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆