简体   繁体   中英

What's the most efficient way to query MongoDB?

I have a MongoDB collection with over 4 million documents. I tried receiving documents the following way.

db.getCollection(collectionName).find(new Document("lang", lang))
        .skip(skip).limit(limit).sort(new Document("date", 1));

took 443 seconds.

db.getCollection(collectionName).find(new Document("lang", lang))
         .sort(new Document("date", 1)).skip(skip).limit(limit);

took 529 seconds.

Both queries delivered exactly the same results.

Was this due to varying network speed? What is the call stack here? I expected the results to be different according to the order of the method calls.

Both query returns the same result. The first one would limit the result improving network IO and then do a sort, while the second would sort on all and then limit the result.

Use indexing to improve query performance. If a query searches multiple fields, create a compound index. Scanning an index is much faster than scanning a collection.

The 2 queries are equivalent. See below example and quote from the db.collection.find() documentation on Combine Cursor Methods.

db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )

The two statements are equivalent; ie the order in which you chain the limit() and the sort() methods is not significant. Both statements return the first five documents, as determined by the ascending sort order on 'name'.

As @Mena suggested the explain command is useful for understanding what a query is doing and the docs also have info on indexing strategies .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM