您可能需要使用聚合框架來獲取結果。考慮運行在蒙戈外殼爲理念的示範如下管道,當然你需要有 實際領域,以取代虛擬字段:
var now = new Date(),
currentMonth = now.getMonth()+1,
pipeline = [
{
"$project": {
"field1": 1,
"field2": 1,
"start_date": 1,
"end_date": 1,
"start_month": { "$month": "$start_date" },
"end_month": { "$month": "$end_date" }
}
},
{
"$match": {
"start_month": { "$lte": currentMonth },
"end_month": { "$gte": currentMonth }
}
}
];
db.collection.aggregate(pipeline);
然後,您可以訪問底層的原始MongoDB的集合爲了使用聚合框架API:
$currentMonth = date("m");
$result = DB::collection('collectionName')->raw(function($collection) {
return $collection->aggregate(array(
array(
"$project"=> array(
"field1" => 1,
"field2" => 1,
"start_date" => 1,
"end_date" => 1,
"start_month" => array("$month" => "$start_date"),
"end_month" => array("$month" => "$end_date")
)
),
array(
"$match"=> array(
"start_month" => array("$lte" => $currentMonth),
"end_month" => array("$gte" => $currentMonth)
)
)
));
});