繁体   English   中英

使用map-reduce / aggregation的MongoDB查询?

[英]MongoDB query using map-reduce/Aggregation?

我在mongo集合中有简单的数据,它看起来像:

{
"_id" : ObjectId("52b73b1318a7be441dbf36b6"),
"nme" : "Vinod Kumar",
"unm" : "vkumar",
"cat" : ISODate("2013-12-22T19:18:43.873Z"),
"act" : [{
    "nme" : "test activity one",
    "dec" : "This is only about test activity",
    "gat" : ISODate("2013-12-25T19:17:00.873Z"),
    "cat" : ISODate("2013-12-22T19:18:43.873Z")
    }]
},

{
"_id" : ObjectId("52b73b1318a7be441dbf36b6"),
"nme" : "Manoj Kumar",
"unm" : "mkumar",
"cat" : ISODate("2013-12-22T19:18:43.873Z"),
"act" : [{
    "nme" : "test activity three",
    "dec" : "This is only about test activity",
    "gat" : ISODate("2013-12-25T19:17:00.873Z"),
    "cat" : ISODate("2013-12-20T19:18:43.873Z")
    },
        {
    "nme" : "test activity two",
    "dec" : "This is only about test activity",
    "gat" : ISODate("2013-12-25T19:17:00.873Z"),
    "cat" : ISODate("2013-12-21T19:18:43.873Z")
    }]
}

我想按(创建时间)和(unm)用户名来获取所有的act(活动)订单。我还想添加分页功能,所以我也需要查询中的限制和偏移量。最后,我期望输出:

        {
    "nme" : "test activity one",
    "dec" : "This is only about test activity",
    "gat" : ISODate("2013-12-25T19:17:00.873Z"),
    "cat" : ISODate("2013-12-22T19:18:43.873Z"),
    "unm" : "vkumar",
    },
        {
    "nme" : "test activity two",
    "dec" : "This is only about test activity",
    "gat" : ISODate("2013-12-25T19:17:00.873Z"),
    "cat" : ISODate("2013-12-21T19:18:43.873Z"),
    "unm" : "mkumar",
    },
        {
    "nme" : "test activity three",
    "dec" : "This is only about test activity",
    "gat" : ISODate("2013-12-25T19:17:00.873Z"),
    "cat" : ISODate("2013-12-20T19:18:43.873Z"),
    "unm" : "mkumar",
    }

我有200000条记录在这个集合中。 谁能在不建议单独创建活动集合的情况下帮助我。

如果有的话,有没有使用聚合框架的解决方法,我该怎么办? 因为我需要使用排序,跳过和限制,所以我不知道如何以最佳性能进行聚合。

我尝试了map reduce,但是这样做没有帮助,因为map reduce将为每个查询生成静态结果,并且使用分页(限制,跳过)时,使用应用程序的多个用户可能会在结果中发生冲突。

任何帮助或建议,将不胜感激。

谢谢

这是我当前的查询

$m = new MongoClient();
$c = $m->selectDB("test")->selectCollection("users");

$ops = array(
array(
    '$project' => array(
        "unm" => 1,
        "act" => 1
    )
),
array('$sort' => array('act.cat' => -1 )),
array('$limit' => 10),

);
$results = $c->aggregate($ops);

这是我自己的问题的答案。 我现在意识到mongo具有隐藏的力量:P

$m = new MongoClient();
$c = $m->selectDB("test")->selectCollection("users");

$ops = array(
array(
'$project' => array(
"unm" => 1,
"act" => 1
)
),
array('$unwind' => '$act'),
array('$match' => array('act.sta' => 1)), // if you want some extra queries. In my case I am checking if status of activity is 1
array('$sort' => array('act.cat' => -1 )), // sort by created time
array('$skip' => $page), // skip int variable
array('$limit' =>$config['per_page']), // limit int variable
);

$results = $c->aggregate($ops); 
print_r($results);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM