I have a collection
db.list.insert({ first: "apple", second: "banana" });
db.list.insert({ first: "apple", second: "tree" });
db.list.insert({ first: "orange", second: "tree" });
db.list.insert({ first: "medal", second: "sport" });
I want to query for documents based on these two fields and fetch documents only when both fields match.
I have tried the following query
db.list.find(
$or: [
{ first: 'apple', second: { $in: ['tree', 'banana']}},
{ first: 'orange', second: { $in: ['tree']}}
],
).limit(5);
and added indexes for
{first: 1, second: 1}
In the query plan, it generates same number of plans as the number of predicates in the "or" query. There are about 2 millions of documents and if it does not get its 5 document in the first predicate then it fetches all the documents matching all the predicates and the query times out. Is there any other efficient way to do this?