排序后如何在MongoDB中进行投影?

时间:2016-11-20 20:21:34

标签: mongodb

<?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class MyController extends Controller { /** * @Route("/get", name="get") */ public function getAction(Request $request) { // Filter/modify the query string, but keep it quite similar: $request->query->remove('some_private_attr'); $my_query_string = http_build_query($request->query->all()); // Setup the curl request: $curl = curl_init('http://localhost?'.$my_query_string); curl_setopt($curl, CURLOPT_HEADER, 1); // Include headers curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // Return data as a string curl_setopt($curl, CURLOPT_PORT, 8200); // Perform the request, returning the raw response // (headers included) as a string: $result = curl_exec($curl); // Get the response status code: $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); // Here, how can I pass the raw external response ($result) // to a new Response object, without parsing the header // and body parts unnecessarily? // Of course, the following doesn't send the right headers: $response = new Response($result, $status_code); return $response; } } 操作字段中可以排除,但如果我想要find然后find,然后sort,那该怎么办?你知道任何技巧,操作吗?

docprojection

1 个答案:

答案 0 :(得分:3)

您可以使用条件,投影和排序运行常用的查询查询。我想你想要对你不想投射的领域进行排序。但是不要担心,即使不投影也可以对该字段进行排序。

如果您明确选择排序字段的投影为&#34; 0&#34;,那么您将无法执行该查找查询。

  //This query will work
  db.collection.find(
  {_id:'someId'},   
  {'someField':1})
  .sort('someOtherField':1)

  //This query won't work
  db.collection.find(
  {_id:'someId'},   
  {'someField':1,'someOtherField':0})
  .sort('someOtherField':1)

但是,如果您仍然无法获得所需的结果,请查看MongoDB Aggregation Framework

以下是根据您的要求进行汇总的示例查询

db.collection.aggregate([
{$match: {_id:'someId'}},
{$sort: {someField:1}},
{$project: {_id:1,someOtherField:1}},
])