在PHP中只使用map而不使用reduce的MongoDB
在mongoDB中,我有两个集合用户和帖子遵循此结构: 职位在PHP中只使用map而不使用reduce的MongoDB,php,mongodb,join,mapreduce,Php,Mongodb,Join,Mapreduce,在mongoDB中,我有两个集合用户和帖子遵循此结构: 职位 { _id: ObjectId(""), subject: "some post", content: "here is the content", user_id: "4351" } 使用者 需要以名称获取数组中的帖子 db.posts.find().map(function(newPost){ newPost.name = db.users.findOne({user_id: new
{
_id: ObjectId(""),
subject: "some post",
content: "here is the content",
user_id: "4351"
}
使用者
需要以名称获取数组中的帖子
db.posts.find().map(function(newPost){
newPost.name = db.users.findOne({user_id: newPost.user_id}).name;
return (newPost);
})
我编写了这段代码,它在mongoshell中工作,并返回以下结果:
{
_id: ObjectId(""),
subject: "some post",
content: "here is the content",
user_id: "4351",
name: "John Marks"
}
但我不能在php中应用。您不能简单地获得map函数的输出。它需要reduce函数和返回值的输出集合
编辑:
$map = new MongoCode('
function(newPost) {
newPost.username = db.users.findOne({user_id: newPost.user_id}).name;
return newPost;
}
');
post = $app->mongo->command(array(
"mapreduce" => "posts",
"map" => $map,
"reduce" => '',
"out" => array("inline" => 1)
));
var_dump($post);
此代码必须有效,但在mongo 2.4发布后,禁止通过“db”访问map函数中的另一个集合。这就是我改变方法的原因。不是使用map/reduce,而是使用php处理。添加了将用户ID发布到数组,并使用以下代码获取用户信息
$userInf = $app->mongo->selectCollection("users")->find(
array('user_id' => array('$in' => $user_ids)),
array("_id" => 0, "user_id" => 1, "name" => 1, "picURL" => 1)
);
我只使用$sales=$db->commandarray-mapreduce=>events,map=>$map,reduce=>$reduce,query=>arraytype=>sale,out=>arraymerge=>eventCounts发现了这种类型的事件;它需要用于reduce函数结果的“out”集合。你什么都没试过?您是否尝试过这些示例,但没有使用$reduce参数,或者使用空函数来完成管道。我尝试过仅使用with map函数作为参数,但在获取数据时,您必须使用$users=$db->SELECTCOLLECT$sales['result']->find;因此,$sales['result']是在map/reduce过程结束时创建的新集合的名称。使用$users=$db->selectCollection$sales['result']->find有什么问题;或者您可以尝试在out参数中使用out=>arrayinline=>1指定内联,并解析结果字符串。好的,我尝试了$post=$app->mongo->commandarray-mapreduce=>posts,map=>$map,reduce=>,out=>arrayinline=>1;var_dump$post;并获取此错误字符串124异常:ReferenceError:db未在't.username=db.users.findOne{user\u id:n'附近的_funcs1 _funcs1:1:49处定义
$userInf = $app->mongo->selectCollection("users")->find(
array('user_id' => array('$in' => $user_ids)),
array("_id" => 0, "user_id" => 1, "name" => 1, "picURL" => 1)
);