0

I have a collection in mongodb and indexed on the field name , i do a free search using the following query to get matched results and limit to 5,

db.getCollection('_event').aggregate([
  {
    "$match": {
      "$and": [
        {
          "$text": {
            "$search": "liver"
          }
        },
        {},
        {}
      ]
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": 1
      },
      "results": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      "count": 1,
      "results": {
        "$slice": [
          "$results",
          5
        ]
      }
    }
  }
])

but there is a data with liverpool . when i do replace it with "$search": "liverpool" it returns data.

what is the issue here?

  • is this a typo? "$search": "liver" – jimmy8ball May 19 '17 at 10:31
  • not a typo , it should return result because it is a free search –  May 19 '17 at 10:32
  • you mean you are looking for all words with liver? – jimmy8ball May 19 '17 at 10:33
  • 1
    from [mongodb documentation](https://docs.mongodb.com/manual/reference/operator/query/text/#match-operation-stemmed-words) : For case insensitive and diacritic insensitive text searches, the $text operator matches on the complete stemmed word. So if a document field contains the word blueberry, a search on the term blue will not match. – felix May 19 '17 at 10:35
  • if you are needing to return all words with liver in it then you need to use a wildcard in the search so: "$search": "*liver*" or at the start of the word "$search": "liver*" – jimmy8ball May 19 '17 at 10:36
  • I think the only way is to use regex in your search, haven't used mongodb in a while though. – George May 19 '17 at 10:36
  • @felix is there a way to do –  May 19 '17 at 10:39
  • 1
    Indirect to the question itself, but the basic concept of what you are trying to do here is very very bad. You are trying to use `$group` to force all of the results into a single document with a results array, and presumably so you can obtain a "total count". Don't do that. If you want paged results and a "total count" then run two separate queries to the server instead. It's the right design and in every single real world usage you are bound to break the BSON limit by trying to force all results into a single document. – Neil Lunn May 19 '17 at 10:40
  • this resource may help - http://stackoverflow.com/questions/26246601/wildcard-string-comparison-in-javascript – jimmy8ball May 19 '17 at 10:42
  • @jimmy8ball how should i replace in my case? –  May 19 '17 at 10:57
  • its important you note the point from @NeilLunn but using a wildcard will return data where a partial match is found using simply "$search": "liver*" – jimmy8ball May 19 '17 at 10:59
  • that is fine, i can combine both –  May 19 '17 at 11:01

0 Answers0