Search code examples
mongodbquery-optimizationmongodb-java

Optimising queries in mongodb


I am working on optimising my queries in mongodb.

In normal sql query there is an order in which where clauses are applied. For e.g. select * from employees where department="dept1" and floor=2 and sex="male", here first department="dept1" is applied, then floor=2 is applied and lastly sex="male".

I was wondering does it happen in a similar way in mongodb. E.g. DbObject search = new BasicDbObject("department", "dept1").put("floor",2).put("sex", "male"); here which match clause will be applied first or infact does mongo work in this manner at all.

This question basically arises from my background with SQL databases.

Please help.


Solution

  • If there are no indexes we have to scan the full collection (collection scan) in order to find the required documents. In your case if you want to apply with order [department, floor and sex] you should create this compound index:

    db.employees.createIndex( { "department": 1, "floor": 1, "sex" : 1 } )
    

    As documentation: https://docs.mongodb.org/manual/core/index-compound/

    db.products.createIndex( { "item": 1, "stock": 1 } )

    The order of the fields in a compound index is very important. In the previous example, the index will contain references to documents sorted first by the values of the item field and, within each value of the item field, sorted by values of the stock field.