返回不同的數據我有很多帖子的「郵報」的收集,我想從post.published_date
的MongoDB:如何使用過濾
返回例如檢索不同YearMonth
值:
['201303', '201301', '201212' ... ... ]
我m使用Symfony2 + DoctrineMongoDB。 我想我必須使用QueryBuilder和map和reduce函數,但我無法使用它們!
任何幫助將不勝感激
感謝
返回不同的數據我有很多帖子的「郵報」的收集,我想從post.published_date
的MongoDB:如何使用過濾
返回例如檢索不同YearMonth
值:
['201303', '201301', '201212' ... ... ]
我m使用Symfony2 + DoctrineMongoDB。 我想我必須使用QueryBuilder和map和reduce函數,但我無法使用它們!
任何幫助將不勝感激
感謝
我建議篩選在客戶端上的日期,但如果你真的需要在服務器上過濾您可以在聚合框架$放鬆/ $ addToSet技巧。事情是這樣的:
db.post.aggregate([
{$match: ...}, // your match here
{$project: {
published_date: 1
}},
{$unwind: "$published_date"},
{$group: {
_id: "$_id",
unique_published_date: {$addToSet: "$published_date"}
}}
])
如果您正在使用的Symfony2和蒙戈DB,您可以創建如下的集合庫,並調用庫函數findDistinctYearMonth
class PostRepository extends DocumentRepository {
public function findDistinctYearMonth()
{
$yearMonths = $this->createQueryBuilder()
->map('function() {
var yearMonth =
emit("" + this.published_date.getFullYear()+("0"+(this.published_date.getMonth()+1)).slice(-2),1);
}')
->reduce('function(k,v) {
return 1;
}')
->getQuery()
->execute();
$arr = array();
foreach($yearMonths as $yearMonth) {
$arr[] = $yearMonth["_id"];
}
return $arr;
}
}
請你能張貼和例如文檔的結構體? – br3w5 2013-03-06 16:05:49