简体   繁体   中英

Optimization - find on all fields in Mongoose MongoDB schema

We needed to challenge our database approach and need your help

We needed to search a word/phrase in all fields of a Mongoose schema.

Let's say the schema is like this:

var sampleSchema = new Schema({
    fieldABC: String,
    fieldDEF: String,
    fieldGHI: String
});

We need to write a find query which will search for a word in all fields in a document of the collection:

db.sampleCollection.find({
  $or: [{
    fieldABC: "wordToSearch"
  }, {
    fieldDEF: "wordToSearch"
  }, {
    fieldGHI: "wordToSearch"
  }]
})

It's possible for us to write the above query but it looks very inefficient - is there some better and faster approach to this?

In the year 2015, it was not supported , is there any change in this?

As suggested by @Veeram

Step 1:

Create a text index

db.sampleCollection.createIndex( { "$**": "text" } )

Step 2:

Use the text index to search the word in concern

db.sampleCollection.find( { $text: { $search: "wordToSearch" } })

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