0

I am using "Wildcard text index" in order to search for a pattern in every fields of my class. I am also using projection in order to remove a certain field:

@Query(value = "{$text: { $search: ?0 }, fields = "{'notWantedField':0}")

However, I would like to prevent from matching something from the unwanted field.

In other words, I would like first to project (and remove fields), then search on the remaining fields.

Is there a way to combine projection and search while keeping the wildcard search?

Thanks a lot.

I am using spring-data-mongodb 1.10.8

Mykeul
  • 498
  • 1
  • 6
  • 20

1 Answers1

1

A possible solution could be a $and operator combined with a $regex.

For example following the Mongodb documentation https://docs.mongodb.com/manual/reference/operator/query/text, if you suppose to create a text index combining subject and author (db.articles.createIndex({"author": "text", "subject": "text"}), you can exclude author field with this query:

db.articles.find( {$and: [{ $text: { $search: "coffee" } }, {"author": {'$regex' : '^((?!coffe).)*$', '$options' : 'i'}}]}, {"author": 0})

In your case, considering that your index is a wildcard, you must exclude, using the regex, all the fields that are also in the projection.

Federico Gatti
  • 535
  • 1
  • 9
  • 22
  • 1
    Thank you. From what I understand, you prevent a match in the excluded field but if it matches another field, we want to consider it as a positive response. Meaning if the string coffee appears in both author and subject fields, it should not be filtered out. – Mykeul Nov 29 '18 at 11:21