[英]MongoDb/PHP, can't get grouping to work right with aggregate framework
我正在嘗試為網站設置消息傳遞收件箱,並且需要將用戶(發送者或接收者)的所有文檔分組到線程中。 郵件集合中充滿了如下文檔:
{
"_id" : ObjectId("4fe8d8ac0a6d2ad9350000d9"),
"message" : "booo",
"recipient" : {
"user_id" : ObjectId("4fd9f0600a6d2ac94f000003"),
"viewed" : 1
},
"sender" : {
"user_id" : ObjectId("4fdb3b780a6d2a9d29000047"),
},
"thread" : "c03a4e49348d009f4ddd8aae325128e1"
"date_sent" : ISODate("2012-06-25T21:31:24.230Z"),
}
我可以使用mongo的group函數來獲得所需的結果,但是您不能對group進行排序或限制,因此,理想情況下,我想使用聚合框架,但是在獲取所需的結果時遇到了麻煩。 基本上我需要這樣做:
$groupBy = array(
'thread' => 1,
);
$initial = array('count' => 0);
$reduce = "function (obj, prev) {
prev.count++;
prev.message = obj.message;
prev.sender = obj.sender.user_id;
prev.recipient = obj.recipient.user_id;
prev.date_sent = obj.date_sent;
prev.viewed = obj.recipient.viewed;
}";
$condition = array(
'$or' => array(
array('sender.user_id' => new MongoId($options['user_id'])),
array('recipient.user_id' => new MongoId($options['user_id']))
)
);
return $this->_collection->group($groupBy, $initial, $reduce, $condition);
使用聚合框架,但我沒有得到所需的結果...基本上,我有以下幾點:
$condition = array(
'$or' => array(
array('sender.user_id' => new MongoId($options['user_id'])),
array('recipient.user_id' => new MongoId($options['user_id']))
)
);
$returnFields = array(
'message' => 1,
'sender.user_id' => 1,
'recipient.user_id' => 1,
'date_sent' => 1,
'thread' => 1,
);
$sort = array('date_sent' => 1);
$groupBy = array('_id' => '$thread');
$input = array(
'aggregate' => $this->_collectionName,
'pipeline' => array(
array('$project' => $returnFields),
array('$match' => $condition),
array('$group' => $groupBy),
array('$sort' => $sort),
)
);
return $this->_db->command($input);
而且它只是返回線程,就像它忽略了我的$ project ...任何想法?
我已經知道了。 雖然不太確定為什么$ project為什么不進行,但是我可以使用$ first運算符在$ group語句中選擇字段
$condition = array(
'$or' => array(
array('sender.user_id' => new MongoId($options['user_id'])),
array('recipient.user_id' => new MongoId($options['user_id']))
)
);
$sort = array('date_sent' => -1);
$groupBy = array(
'_id' => '$thread',
'sender' => array('$first' => '$sender.user_id'),
'recipient' => array('$first' => '$recipient.user_id'),
'date_sent' => array('$first' => '$date_sent'),
'message' => array('$first' => '$message'),
'viewed' => array('$first' => '$recipient.viewed'),
);
$input = array(
'aggregate' => $this->_collectionName,
'pipeline' => array(
array('$match' => $condition),
array('$sort' => $sort),
array('$group' => $groupBy),
array('$sort' => $sort),
)
);
return $this->_db->command($input);
基本上,我需要匹配正確的文檔,對它們進行排序,以便最先顯示最新消息,然后執行$ group,在這里我可以使用$ first運算符選擇字段,然后再次對它們進行排序,以便它們以正確的順序排列。 認為這不是必需的,但這似乎可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.