0

Hi is it possible make query which find in this data set

{ "text" : "cake" }
{ "text" : "sale" }
{ "text" : "sale cake" }
{ "text" : "cake sale" }
{ "text" : "dress sale" }
{ "text" : "cake sale monday"

All documents excluding word "monday"

I want get result like this:

{ "text" : "cake" }
{ "text" : "sale" }
{ "text" : "sale cake" }
{ "text" : "cake sale" }
{ "text" : "dress sale" }
{ "text" : "cake sale" }
user2264784
  • 447
  • 1
  • 5
  • 15
  • What have you tried so far? Where are you stuck? Also: It's a bit unclear exactly what you're trying to do. In your example, you're showing one single modification in the result set: A truncated string. This isn't really a "find" - this is a transform (e.g. changing string content). Is that truly the case? Also, will your content be stored as free-form text like shown (vs, say, an array of keywords?) – David Makogon Mar 24 '18 at 09:50
  • I have search field on front-end, And I want to use search query like "Not some string". If I want sort all product exclude product which contains word "Cake", only meat, apple ... – user2264784 Mar 24 '18 at 15:58
  • Stored as free-form text – user2264784 Mar 24 '18 at 15:58

2 Answers2

0

You can try using MongoDB regex. Sample Query

db.example.find({text:{$not:/monday/, $regex:/cake/}})

Please refer to this on MongoDB regex performance.

Pardeep Singh
  • 412
  • 3
  • 14
  • If I will write like this: I will miss { "text" : "sale" } and { "text" : "dress sale" } – user2264784 Mar 24 '18 at 15:55
  • I think then for a free-form search you should rather use some search engine like Elasticsearch and Solar which are optimized for free-form search queries. This query was just to demonstrate how it can be done with MongoDB regex. – Pardeep Singh Mar 24 '18 at 17:42
0

You can use MongoDB Text search also. First, you need to create a text search index.

Create index on books collection for title and category fields

db.books.createIndex({title:'text', category:'text'})

Then search using $text operator like

db.books.find({$text:{$search: 'mongodb'}}).pretty()

Above query will search for mongodb text in both title and category field.

If you want to search for mongodb text but want to exclude results which contains beginner word this can be done by using - as a prefix to beginner word

db.books.find({$text:{$search: 'mongodb -beginner'}}).pretty()

Refer to $text Documentation for more.

Pardeep Singh
  • 412
  • 3
  • 14