dobeerman
dobeerman

Reputation: 1424

How to query MongoDB with "LIKE" and "NOT LIKE"?

I've an array like this

array(
  'ts' : 123456789,
  'nm' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
)
...
array(
  'ts' : 122345678,
  'nm' : 'Nulla lorem purus, pretium porttitor ultricies sit amet, rutrum sollicitudin risus.'
)

How to find elements who contains 'amet' AND not contains 'ipsum' in 'nm'? And how to find elements who contais both 'amet' and 'ipsum' ?

Upvotes: 1

Views: 4187

Answers (2)

dobeerman
dobeerman

Reputation: 1424

MY SOLUTION

array(
  'nm' => array(
    '$all' => array(new MongoRegex('/amet/'), ...),
    '$nin' => array(new MongoRegex('/ipsum/'), ...)
  )
)

Upvotes: 2

Theo
Theo

Reputation: 132862

The closest thing Mongo has to LIKE is regexes:

db.my_collection.find({nm: /amet/})

but I don't think you can do what you ask for unless you can write a single regex that captures both the contains and not-contains part of your query.

That said, just as with LIKE, Mongo's regex queries are not performant. If you need full text search you should look to something like Solr, or a database that has full text indexes built in.

Upvotes: 1

Related Questions