Compass and variables

I cannot find anything about how to use variables successfully in Compass.
This follows the solution that works in Terminal, but will not work in Compass:

The variable will not be recognized in the following step.

Thanks,
Austin

Hi @Austin_Summers,

You can’t use variables in your Compass pipelines. You can only do so in your back-end code when you export the pipeline into your actual production code.

Using the $addFields stage before the $match stage is also a bad idea because it prevents the $match stage from using an index on the cast field that is required for this query.

So the correct pipeline for this query is:

db.movies.aggregate([{$match: { cast: { $in: [ "Sandra Bullock", "Tom Hanks"]}}}])

But at this point, a regular find would be enough.

db.movies.find({ cast: { $in: [ "Sandra Bullock", "Tom Hanks"] } })

Cheers,
Maxime.

1 Like

Thanks, Maxime.

As someone coming from the relational DB side, I am noticing the constraints of Compass.
Is there a code editor that allows me to use variables and run the full spectrum of code?

Austin

Compass is useful to prototype and debug pipeline before inserting them in your production code. That’s also the reason why the “sampling” mode is activated by default.

There are options at the top to import pipeline from text and export to code.

I think I would just use any code editor (VS code or Webstorm) and JS files with variables in there.

Then it’s easy to execute that JS file using Mongosh and print the result in the console.

See this doc:

Cheers,
Maxime