2

In a collection subject, in which the documents have social,maths and english as fields. If I need to provide a hint to the following find query, how do I do it?

db.subject.find({maths : 30, social :10,english : 20});
Christian P
  • 12,032
  • 6
  • 60
  • 71
  • 2
    Hints are provided using index names. You didn't tell us what indexes you have, or if you have any. – Christian P Jun 25 '14 at 07:09
  • 1
    @ChristianP You can actually supply an index specification like: `{d:1, c:-1}` to hint which none of the answers below have said – Sammaye Jun 25 '14 at 07:21
  • @Sammaye you are correct, as always. I forgot to mention that in my comment, but the answers quickly pointed that out, so it was redundant for me to write it :) – Christian P Jun 25 '14 at 07:23
  • @ChristianP I have indexes but cant we specify hints using fields rather than the index names? –  Jun 25 '14 at 07:37
  • You can also specify hint using fields (look at the answers). – Christian P Jun 25 '14 at 07:40

3 Answers3

3

You can try this, I haven't tested it :

BasicDBObject query = new BasicDBObject("maths", 30)
                     .append("social",10).append("english",20);
DBCursor cursor = collection.find(query).hint(new BasicDBObject(index , 1));
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
3

From the docs (http://docs.mongodb.org/manual/reference/method/cursor.hint/#cursor.hint)

db.subject.find({maths : 30, social :10,english : 20}).hint({maths : 1}) or any other index

Jeff Tsui
  • 1,266
  • 12
  • 20
  • i need to add multiple fields to the index, when i do so it is throwing bad hint error –  Jun 25 '14 at 07:35
0

I had created index from command line. I tried this from Java,

Query searchQuery = new Query(Criteria.where("maths").is(30));
searchQuery.withHint("index_name");
Madhu
  • 53
  • 1
  • 11