簡體   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