Random record from MongoDB

后端 未结 27 2659
栀梦
栀梦 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:36

    You can also use MongoDB's geospatial indexing feature to select the documents 'nearest' to a random number.

    First, enable geospatial indexing on a collection:

    db.docs.ensureIndex( { random_point: '2d' } )
    

    To create a bunch of documents with random points on the X-axis:

    for ( i = 0; i < 10; ++i ) {
        db.docs.insert( { key: i, random_point: [Math.random(), 0] } );
    }
    

    Then you can get a random document from the collection like this:

    db.docs.findOne( { random_point : { $near : [Math.random(), 0] } } )
    

    Or you can retrieve several document nearest to a random point:

    db.docs.find( { random_point : { $near : [Math.random(), 0] } } ).limit( 4 )
    

    This requires only one query and no null checks, plus the code is clean, simple and flexible. You could even use the Y-axis of the geopoint to add a second randomness dimension to your query.

提交回复
热议问题