Mixing MongoDB request types (and, or)

I use MongoDB to store coffee information, and I am having query problems.

My document structure:

{ _id: "Thailand Bok", tags: ["Strong", "Smooth", "Dark"] }

I am trying to create a query that allows me to search either by name or by tags.

Therefore, if the query string can be "Thailand Bok" or ["Strong", "Smooth"], I want to search for queries containing either _id or each tag.

If I were thinking in terms of SQL, it could be something like this:

"WHERE `_id` like 'Not present%' OR ("Strong" IN `tags` AND "Smooth" IN `tags`)"

The query that I still have is:

{ 
    $or: [
      { _id: { $regex: '^Not present', '$options': 'i' } },
      { 
          $and: [ 
              { tags: 'Strong' }, 
              { tags: 'Smooth' } 
          ]
      }
    ]
}

edit: fix the error in the request and clarify that it should work either if _id matches OR tags that match

+3
source share
2 answers

$ and is supported only in MongoDB version 2.0+ I used 1.8.2

+7
source

You ask for everything except using curly braces instead of square brackets for $ or.

{$or: [
  {_id: {$regex: '^hailand', $options: 'i'} }, 
  {'$and': [
       {tags: 'Strong'}, 
       {tags: 'Smooth'}
   ]}
]}

It works well.

+5
source

All Articles