您可以采用的一种方法是使用底层驱动程序提供的原始 MongoDB 集合对象中的聚合框架方法。在 mongo shell 中,您实际上将运行以下聚合管道操作来比较两个字段并返回满足该条件的文档:
db.collection.aggregate([
{
"$project": {
"isMatch": { "$eq" : ["$total", "$remaining"] }, // similar to "valueof(total) == valueof(remaining)"
"id" : 1,
"title" : 1,
"summary" : 1,
"total" : 1,
"remaining" : 1,
"status" : 1
}
},
{
"$match": { "isMatch": true } // filter to get documents that only satisfy "valueof(total) == valueof(remaining)"
}
]);
或者在 find() 查询中使用 $where 运算符:
db.collection.find({ "$where" : "this.total == this.remaining" })
因此在 laravel 中,您可以使用 raw expressions 获取文档,如下所示
$result = DB::collection("collectionName") -> raw(function ($collection)
{
return $collection->aggregate(array(
array(
"$project" => array(
"id" => 1,
"title" => 1,
"summary" => 1,
"total" => 1,
"remaining" => 1,
"status" => 1,
"isMatch" => array(
"$eq" => array( "$total", "$remaining" )
)
)
),
array(
"$match" => array(
"isMatch" => true
)
)
));
});
对于$where,您可以将表达式直接注入到查询中:
Model::whereRaw(array("$where" => "this.total == this.remaining"))->get();
或者在查询构建器上执行的内部 MongoCollection 对象上使用原始表达式。请注意,使用 raw() 方法需要使用游标,因为它是低级调用:
$result = Model::raw()->find(array("$where" => "this.total == this.remaining"));