如何对文档中的内部数组进行排序?

我正在通过 $push 在我的文档中的一个数组中进行“插入”,其中有一个字段日期,我想在使用 find() 时对其进行排序,但不对“_id”进行排序。如何按日期排序 (ordens.dtOrdem)?


    <?php

        $mongo = (new MongoDB\Client('mongodb://localhost:27017'))->Carteira;

        $collection = $mongo->ativo;


        /*First way that I've tried*/

        $result1 = $collection->find([].['ordens' => ['sort' => ['dtOrdem' => -1]]]);


   /*Second way that I've tried*/

   $result2 = $collection->find([],['ordens' => ['each' => ['ordens' => ['sort' => ['dtOrdem' = -1]]]]]);

?>

字段“ordens.dtOrdem”未按降序排序。


PIPIONE
浏览 182回答 1
1回答

慕码人2483693

您不能在find().&nbsp;你有两个选择:您可以$sort在您的过程中指定一个操作,$push以确保您的元素按排序顺序添加到数组中。您可以使用聚合在检索时对数组进行排序。解决方案可能类似于以下内容(可能需要进行一些修改):// Sorting on push.$collection->updateOne(&nbsp; &nbsp; [...],&nbsp; &nbsp; [ '$push' => [&nbsp; &nbsp; &nbsp; &nbsp; 'ordens' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // You MUST include the $each operator here or this will not work.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '$each' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [ 'dtOrdem' => 5 ]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Where the magic happens, sorts in descending order.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '$sort'=> [ 'dtOrdem' => -1 ]&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; ]]);// Sorting on retrieval.$collection->aggregate([&nbsp; &nbsp; [ '$unwind' => '$ordens' ],&nbsp; &nbsp; [ '$sort' => [&nbsp; &nbsp; &nbsp; &nbsp; '$ordens.dtOrdem' => -1&nbsp; &nbsp; ]],&nbsp; &nbsp; [ '$group' => [&nbsp; &nbsp; &nbsp; &nbsp; '_id' => '$_id',&nbsp; &nbsp; &nbsp; &nbsp; 'ordens' => [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '$push' => '$ordens'&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; ]]]);
打开App,查看更多内容
随时随地看视频慕课网APP