Random record from MongoDB

后端 未结 27 1921
栀梦
栀梦 2020-11-22 01:22

I am looking to get a random record from a huge (100 million record) mongodb.

What is the fastest and most efficient way to do so? The data is already t

27条回答
  •  孤独总比滥情好
    2020-11-22 01:38

    My PHP/MongoDB sort/order by RANDOM solution. Hope this helps anyone.

    Note: I have numeric ID's within my MongoDB collection that refer to a MySQL database record.

    First I create an array with 10 randomly generated numbers

        $randomNumbers = [];
        for($i = 0; $i < 10; $i++){
            $randomNumbers[] = rand(0,1000);
        }
    

    In my aggregation I use the $addField pipeline operator combined with $arrayElemAt and $mod (modulus). The modulus operator will give me a number from 0 - 9 which I then use to pick a number from the array with random generated numbers.

        $aggregate[] = [
            '$addFields' => [
                'random_sort' => [ '$arrayElemAt' => [ $randomNumbers, [ '$mod' => [ '$my_numeric_mysql_id', 10 ] ] ] ],
            ],
        ];
    

    After that you can use the sort Pipeline.

        $aggregate[] = [
            '$sort' => [
                'random_sort' => 1
            ]
        ];
    

提交回复
热议问题