4

MongoDB seems to only do logical OR text queries?

If I want to find all documents that contain the words ('apple' or 'orange' or 'pear') I can do the following.

db.collection.runCommand('text', {search: 'apple orange pear', limit: -1})

But how do I find all documents that contain all 3 of the words ('apple' and 'orange' and 'pear') in no particular order.

Is this possible?

ajduke
  • 4,991
  • 7
  • 36
  • 56
Cathal Coffey
  • 1,105
  • 2
  • 20
  • 35
  • Check this answer out as a workaround for supporting logical `AND` queries by wrapping each single search term with double quotes: http://stackoverflow.com/a/35641331/1123355 – Elad Nava Feb 26 '16 at 15:55

2 Answers2

5

Logical AND operation can be done like this

"\"word1\" \"word2\""

in your example, hence: "\"apple\" \"orange" \"pear""

annakeuchenius
  • 195
  • 2
  • 8
  • this is not working at present, means it is returning All apple and all orange records db.getCollection('myCollection').find({"$text" :{ "$search" : "\"apple\" \"orange\" " }}), can u help me. – Satish Oct 25 '18 at 19:54
-2

Yes it is possible to do that. Please refer the documentation here - http://docs.mongodb.org/manual/tutorial/search-for-text/#match-phrases

For your query it should look something like this...

db.collection.runCommand('text', { search : "('apple') AND ('orange') AND
                                             ('pear')", limit : 1 });
SridharVenkat
  • 656
  • 8
  • 21
  • I don't think that is right, you link is right but you have taken the explanation example and not the code example – Sammaye Oct 08 '13 at 07:33
  • @Sammaye, i didn't get you.. are you saying the code above is wrong?, i tested it did work in my db... – SridharVenkat Oct 08 '13 at 09:02
  • Are you totally sure or did it just search in a different way? Read the entire seciton you will see what I mean – Sammaye Oct 08 '13 at 09:04
  • yes i am sure... for IP reasons i couldn't put the queries i tried in my application. Each time i searched it gave me results matching all the strings.. Let me know if you finding any issues? – SridharVenkat Oct 08 '13 at 09:06
  • Would by any chance also give results match any of the strings? Unless the `'` are the same as `"` when translated – Sammaye Oct 08 '13 at 09:23
  • 14
    To make it easier, the answer your looking for is: `"\"apple\" \"orange\" \"pear\""` – Sammaye Oct 08 '13 at 09:25
  • Sammaye you are correct. The text command performs a compound logical AND of phrases. Where the syntax for a phase is \"phrase\". – Cathal Coffey Oct 08 '13 at 18:06
  • @CathalCoffey would you mind pasting the final(solved) query here... it will help.. – SridharVenkat Oct 10 '13 at 02:07