Monday, May 6, 2013

How to find random documents with Mongoose? [Get random data with MongoDb]

Mongoose is an ORM module for node.js that give you utility to create ORM database with no-sql database MongoDB. NoSql database has a lot of pros come with it, but has a lot of cons too. For example RDBMS can Select * From rand(), mongodb can't do that.

Yes, you can't find random document in mongodb. But I have found how to create schema that able to find it by random. Here is mine:


var exampleSchema  = new Schema({
name: String,
random_point: {type: Schema.Types.Mixed, default: [Math.random(), 0]}
}); 
Insert some documents: 
var Example  = mongoose.model('Example', exampleSchema);
var example = new Example({ name: "Testa", random_point: [Math.random(), 0] });
example.save(function (err) {
  if (err) // ...
  console.log('testa successfull');
});
And you can find it by random: 
Example.find({random_point: {$near: [Math.random(), 0] }}, function(error, result){console.log(result); })
Actually for mongodb this requires only one query and no null checks, and the code is cleaner, simpler and more flexible. for example:


// Enable geospatial indexing on a collection
db.docs.ensureIndex( { random_point: '2d' } )

// 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] } );

// Get a random document
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 )



No comments:

Post a Comment