0

I want to use the match pipeline stage to dynamically filter based on given parameters that may or may not be undefined when I call the function.

For example, if I passed in a JSON object to the function that contains a value for Field1, I would have a match pipeline like the following:

        {
        "$match": {
            "Field1": Field1_value
        }}

However, if I had a JSON object passed into the function that contains values for Field1 and Field 2, I would like to have a match pipeline like the following:

        {
        "$match": {
            "Field1": Field1_value,
            "Field2": Field2_value
        }}

Is there a simple way to do this that wouldn't involve having to write static pipelines for each combination of fields that I pass to this function?

2

1 Answer 1

0

I am assuming your are not programming in pure Mongo. If so, you could use whatever else you are using to prepare the $match object.

here is an Example on Javascript

var pipeline = function(parameters){
    return [
        {
        $match:parameters,
        }
        // put here other stages
    ]
};

// first call
collection.aggregate(
    pipeline({"Field1": Field1_value}), options, callback
);
// second call
collection.aggregate(
    pipeline({"Field1": Field1_value, "Field2": Field2_value}), options, callback
)

If the $match operation is not the first of your pipeline and depends of a previous operation, I think it is not possible to do it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.