Srinjoy Choudhury
Srinjoy Choudhury

Reputation: 831

Spring MongoDB query performances

I want to understand in depth how the springframeworks mongodb works

so assume i have a index in my database a compound index of 2 fields a,b

Now these are the queries i write i want to know which of these will hit the index and some idea on performance and which is the best type to use

1. Query q = new Query()
    query.addCriteria(Criteria.where(a).is("val")); 
    query.addCriteria(Criteria.where(b).is("val2"));

2. query.addCriteria(Criteria.where(a).is("val").andOperator(Criteria.where(b).is("val2")))

3. query.addCriteria(Criteria.where(a).is("val").and(b).is("val2"))

What is the difference between 2 and 3. Will all of these variation hit the correct index Some Best Practices around the same

Upvotes: 0

Views: 1874

Answers (1)

Valijon
Valijon

Reputation: 13113

Spring-Data (MongoDB) does not influence the decision of how the query should be executed.

For a query, the MongoDB (server) query optimizer chooses and caches the most efficient query plan given the available indexes

Reference: Query Plans

Exception:

Call cursor.hint(index) on a query to override MongoDB's default index selection and query optimization process

Answering to your question: Query planner chooses the best strategy based on your query. No matter how you define it, MongoDB will analyze it and shape it before the execution.

They are equivalent for MongoDB:

{"a": "val", "b":"val2"} 
{"a": "val", "$and":[{"b":"val2"}]} 
{"$and":[{"a": "val"}, {"b":"val2"}]} 

Run db.collection.find({...}).explain() for each query for more details.

Upvotes: 3

Related Questions