How to evaluate simple expressions

Viewed 93

When developing complex aggregations, I want the ability to test out simpler expressions as a sanity check. So I'm wondering if mongo shell has the ability to evaluate simple expressions.

For example, I want to do simple things like:

> { $hour: ISODate("2016-01-01T12:30:00Z") }
ISODate("2016-01-01T12:30:00Z")

In the example above it seems the shell isn't evaluating and returning the hour component as desired.

Is it possible to do what I want here?

2 Answers

If you're willing to use something other than Mongo Shell, NoSQLBooster will evaluate partial query operations. Just highlight the relevant section and click Run.

This is particularly useful for constructing pipelines with multiple stages. You can evaluate your pipeline one stage a time to verify which documents are passed to the next stage.

enter image description here

Not an ideal solution, but you can something like this:

var exprr = { "$hour": ISODate("2016-01-01T12:30:00Z") };

var tempCollection = "tempCollection";
db.getCollection(tempCollection).insert({});
db.getCollection(tempCollection).aggregate([
    {"$project" : {"_id" : 0, "result" : exprr}} 
]);
db.getCollection(tempCollection).drop();

Or you can wrap last part in a function and save it, for resue. The idea is we will make a temporary collection, insert a blank document on it and evaluate an expression the aggregation way. The downside is you can only evaluate those expressions which are supported in project aggregation operation.

Related