stackers
stackers

Reputation: 3280

Mongoose $match any value

Based on user input I want to search my db for documents where the type is one of several values. If the input is equal to 'any', I want to it to return documents where the type is equal to anything.

My $match is part of an aggregate pipleline. I just want to do something like this, where the value I set to inputType will cause the $match to return all documents regardless of their type value.

 if (inputType == 'any')
 inputType = '*';

{"$match": { 
  type: inputType, 
}}

Is there anything like this? Or perhaps a better way to do this?

Upvotes: 2

Views: 2156

Answers (2)

stackers
stackers

Reputation: 3280

Found that you could use regular expressions. This does the job:

inputType = /.*/g;

Upvotes: 0

kkkkkkk
kkkkkkk

Reputation: 7748

You could do this:

if (inputType === 'any') {
  inputType = {
    $exists: true
  };
}

db.collection.aggregate([
  {
    $match: { 
      type: inputType, 
    }
  }
]);

Upvotes: 2

Related Questions