search

Home  >  Q&A  >  body text

mongodb子文档排序的问题

Array(
    [id] => 00008
    [game] => Array
        (
            [0] => Array
                (
                    [gid] => 02569
                    [date] => 1363583244
                )

            [1] => Array
                (
                    [gid] => 04001
                    [date] => 1363339740
                )
        )
)
Array(
    [id] => 00010
    [game] => Array
        (
            [0] => Array
                (
                    [gid] => 02569
                    [date] => 1363583244
                )

            [1] => Array
                (
                    [gid] => 04028
                    [date] => 1363889740
                )
        )
)

上面是众多结果当中的2个。我现在的需求是从所有结果当中找到gid = 02569的,并且按照对应的date进行DESC排序

伊谢尔伦伊谢尔伦2767 days ago632

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-21 11:19:14

    Similarly implemented using the aggregate framework (for reference only, not tested). Available with mongodb 2.2+.

    db.xxx.aggregate([
        {
            $match: {'game.gid': 02569}
        },
        {
            $sort: {$date: -1}
        }
    ])

    reply
    0
  • 黄舟

    黄舟2017-04-21 11:19:14

    What do you want to rank? The whole doc? Or doc.game? In other words, does it only look at the game level?

    If you want to sort sub-documents, just use the aggregation framework. But an unwind should be added upstairs, and the key of sort is wrong, it should be game.date.

    php’s aggregation framework documentation: http://www.php.net/manual/en/mongocollection.aggregate.php

    reply
    0
  • Cancelreply