为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
PIPIONE 2022-01-08 17:33:37
我正在通过 $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”未按降序排序。
查看完整描述

1 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

您不能在find(). 你有两个选择:

  1. 您可以$sort在您的过程中指定一个操作,$push以确保您的元素按排序顺序添加到数组中。

  2. 您可以使用聚合在检索时对数组进行排序。

解决方案可能类似于以下内容(可能需要进行一些修改):

// Sorting on push.

$collection->updateOne(

    [...],

    [ '$push' => [

        'ordens' => [

            // You MUST include the $each operator here or this will not work.

            '$each' => [

                [ 'dtOrdem' => 5 ]

            ],


            // Where the magic happens, sorts in descending order.

            '$sort'=> [ 'dtOrdem' => -1 ]

        ]

    ]]

);


// Sorting on retrieval.

$collection->aggregate([

    [ '$unwind' => '$ordens' ],

    [ '$sort' => [

        '$ordens.dtOrdem' => -1

    ]],

    [ '$group' => [

        '_id' => '$_id',

        'ordens' => [

            '$push' => '$ordens'

        ]

    ]]

]);


查看完整回答
反对 回复 2022-01-08
  • 1 回答
  • 0 关注
  • 181 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号