Doom
Doom

Reputation: 1278

Mongo DB Find with orderby

i have make this query on db with 3.000.000 of record and size of 3GB:

int toskip=5000;
int limit=100;
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "mydb" );
DBCollection collection = db.getCollection("mycollection");
BasicDBObject query = new BasicDBObject("idfile",idfile);
BasicDBObject orderBy = new BasicDBObject("idrow",1);
List<DBObject> listElem = collection.find(query).sort(orderBy).skip(toskip).limit(limit).toArray();
mongoClient.close();

but not work because runs out of memory. Is correct my query? Thanks.

Upvotes: 0

Views: 832

Answers (1)

attish
attish

Reputation: 3150

You have to define an index to fast up things. There are 4 possiblities.

If you have an index support for the query so an index on idfile it will fast up the query part but will not support the sorting after, so you will have to face with slow sorting if the query has big resultset. (Exactly as Sammaye mentioned). Due to this way the index is 'small' this can be a good way.

In case if you have an index for the sorting phase you will run a full scan on the collection which probably always worth then the first case.

Having a compound index on (check the documentation) {idfile:1, idrow:1} will help, till you not likely to run range based query or something like this. While you querying only for a single field single value pair it will work and will fast up both the query and the sorting.

If you likely to run a query which get several values for the idfile, it is worth to consider to create a compound index like {idrow:1, idfile:1} with this the sorting phase will supported by the structure of the index and lots of documents will be excluded for the scanning. Just something to test.

Upvotes: 1

Related Questions