我在MongoDB中有一个集合“activity_logs”,其中包含以下数据,
{
"_id": "lg1",
"action": "create_event",
"business_id": "bs1",
"event_id": "event1",
"log_date": ISODate("2015-08-20T19:30:46.0Z")
},
{
"_id": "lg2",
"action": "create_deal",
"business_id": "bs1",
"deal_id": "deal1",
"log_date": ISODate("2015-08-17T19:20:46.0Z")
},
{
"_id": "lg3",
"action": "deal_used",
"cust_id": "cust1",
"business_id": "bs1",
"deal_id": "deal1",
"log_date": ISODate("2015-08-17T19:25:46.0Z")
},
{
"_id": "lg3",
"action": "deal_used",
"cust_id": "cust2",
"business_id": "bs1",
"deal_id": "deal1",
"log_date": ISODate("2015-08-18T11:25:46.0Z")
},
{
"_id": "lg4",
"action": "create_deal",
"business_id": "bs1",
"deal_id": "deal2",
"log_date": ISODate("2015-08-18T19:20:46.0Z")
},
{
"_id": "lg5",
"action": "create_deal",
"business_id": "bs2",
"deal_id": "deal3",
"log_date": ISODate("2015-08-19T19:20:46.0Z")
},
{
"_id": "lg6",
"action": "create_events",
"business_id": "bs3",
"event_id": "event5",
"log_date": ISODate("2015-07-18T19:22:46.0Z")
},
{
"_id": "lg7",
"action": "deal_used",
"business_id": "bs2",
"cust_id": "cust5"
"deal_id": "deal3",
"log_date": ISODate("2015-08-17T19:20:46.0Z")
}
我想通过该商家采取的一系列行动获取所有记录。最新的第一 如果商家创建任何最新的交易,那么我需要显示 xyx创建新的交易1 , 如果2个客户使用该交易,那么我想显示 2个用户使用xyz业务的交易1 。
所以输出看起来像,
business_id action deal_id event_id users_count log_date
bs1 create_event - event1 - ISODate("2015-08-20T19:30:46.0Z")
bs2 create_deal deal3 - - ISODate("2015-08-19T19:20:46.0Z")
bs3 create_event - event5 - ISODate("2015-07-18T19:22:46.0Z")
bs1 create_deal deal2 - - ISODate("2015-07-18T19:20:46.0Z")
bs1 deal_used deal2 - 2 ISODate("2015-07-18T11:25:46.0Z")
bs1 create_deal deal1 - - ISODate("2015-08-17T19:20:46.0Z")
bs2 deal_used deal3 - - ISODate("2015-08-17T19:20:46.0Z")
输出将是行动,交易,事件,专业组。
我尝试过以下查询,但这并不满足所有,
db.activity_logs.group({
"key": {
"action": true,
"shared_action": true,
"business_id": true,
"event_id": true,
"deals_id": true,
"deal_id": true
},
"initial": {
"count_id": 0
},
"reduce": function(obj, prev) {
if (obj._id != null) if (obj._id instanceof Array) prev.count_id += obj._id.length;
else prev.count_id++;
}
});
请帮我一样。 并建议我如果我可以使用聚合。
答案 0 :(得分:0)
经过大量研究后,我发现了我的问题的答案。我发布它只是为了帮助面临这些困难的其他人,
$array = array(
array('$project' => array( '_id' => 1,'action'=>1, 'business_id'=>1,'event_id' => 1, 'deal_id' => 1, 'cust_id' => 1,'log_date' => 1)),
array('$group' => array("_id" => array('action' => '$action',"pro_id" => '$pro_id',"event_id" => '$event_id', "deal_id" => '$deal_id'),'count' => array('$sum' => 1),'lastDate' => array( '$last' => '$log_date'))),
array('$skip'=>$list),
array('$limit'=>1000),
array('$sort'=>array('log_date'=> -1)),
);
$results = $collection_activity_logs->aggregate($array);