简体   繁体   中英

get list of collections having all words exists in field which added in given string in mongoDB

I want to search list of collections from mongoDB have all the keywords of given string.

For eg

I have a collection 
{
  "id":1
  "text":"go for shopping",
  "description":"you can visit this branch as well"
}
{
  "id":2
  "text":"check exiting discount",
  "description":"We have various discount options"
}

Now, If I will pass string like wrt text field in find query of mongoDB. 字符串的文本字段。 Then I should get first collection as output because text field value "go for shopping" exists in the input string passed in find query.

You can do so through regular expression. MongoDb provides the provision of matching strings through regex patterns. In your case you could do something like:

db.yourCollectionName.find({text:{$regex:"go for shopping" }})

This will return you all the documents having the phrase "go for shopping" in the text field.

Ref: MongoDb Regex

This can be achieved through $text operator in MongoDB. But you have to createIndex on the "text" field in your database.(or whichever filed you want to be matched, I would suggest you rename it in your db to avoid confusion)

db.yourCollectionName.createIndex({"text":"text"})

The first field here is the "text" field in your database, and the second one is the mongo operator.

Then you can pass any query like,

db.yourCollectionName.find({$text: {$search: "I want to go for shopping"}})

The "$text" here is the mongo operator. This would return all documents which have any of the keywords above.

Maybe you can read more around this and improvise and modify.

Ref: MongoDb $text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM