1

i have the following collection:

books> db.books.find()
[
  {
    _id: ObjectId("61ab85b0056b5357b5e23e6b"),
    fields: 'hello good morning'
  },
  { _id: ObjectId("61ab85b5056b5357b5e23e6c"), fields: 'good morning' },
  {
    _id: ObjectId("61ab8679056b5357b5e23e6d"),
    fields: 'hello good morning guys'
  },
  {
    _id: ObjectId("61ab8684056b5357b5e23e6e"),
    fields: 'good morning guys'
  }
]

Then, i run this query:

db.books.find({$text : {$search : "\"good morning\" hello"}})

and i get:

[
  { _id: ObjectId("61ab85b5056b5357b5e23e6c"), fields: 'good morning' },
  {
    _id: ObjectId("61ab8684056b5357b5e23e6e"),
    fields: 'good morning guys'
  },
  {
    _id: ObjectId("61ab85b0056b5357b5e23e6b"),
    fields: 'hello good morning'
  },
  {
    _id: ObjectId("61ab8679056b5357b5e23e6d"),
    fields: 'hello good morning guys'
  }
]

Can you help me to understand the output? The first result doesn't make much sense to me (document _id : ...23e6c), as it doesn't contain the "hello" string.

I read the first answer to this question. Does it mean that, in my case, mongodb is searching for

(good morning) AND (good OR morning OR hello)

It would explain my question, but i can't find the exact reference to this in the mongodb documentation

Thanks in advance

rekotc
  • 595
  • 1
  • 10
  • 21

1 Answers1

1

Directly from the docs:

A string of terms that MongoDB parses and uses to query the text index. MongoDB performs a logical OR search of the terms unless specified as a phrase. See Behavior for more information on the field.

This is just the behavior a text index allows, What you can do it mark every single expression as a "phrase", like so:

{$text : {$search : "\"good morning\" \"hello\""}}

This will enforce $and logic.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • In the same page of the documentation, i also read that "If the $search string includes a phrase and individual terms, text search will only match the documents that include the phrase.". Do i correctly understand that, by including a phrase in the search string, mongodb will ignore any additional individual term? It would also explain my output. – rekotc Dec 05 '21 at 11:18
  • 1
    Yep, you understood it correctly. i edited my answer to reflect that as a better solution. – Tom Slabbaert Dec 05 '21 at 11:40