Is it possible to use the Mongoose query builder to simply return an array of pipelined aggregates and not start the query?

I work locally - it will never be done on a live website. I built a node / express server that will accept a strict aggregation pipeline for Mongo and return the results to the browser:

app.get('/aggregate/:collection', function(req, res) { var queryObject = JSON.parse(req.param('q')); var recProvider = getProviderForTable(req.params.collection); recProvider.getCollection(function(err, collection) { collection.aggregate(queryObject, {}, function(err, data) { res.json(data); }); }); }); 

This allows you to make quick queries in a browser, where I create a data visualization:

 $.get(LOCAL_SERVER + '/aggregate/my_records?q=' + JSON.stringify(pipeline)); 

I almost started building a query builder like Mongoose, but just to create an array of pipelined aggregates. I am wondering if I can use the Mongoose query builder in the browser only to create an array, and then use it to hit my express server for the data as above?

I want to build a chain object, for example ...

 pipeline() .where('value').gt(1000) .where('category').in([1, 2, 3]) .sort('-date') .skip(100).limit(10); 

... will return the aggregation pipeline:

 [ { $match: { value: { $gt: 1000 }, category: { $in: [1, 2, 3] } } }, { $sort: { date: -1 } }, { $skip: 100, $limit: 10 } ] 
+4
source share
1 answer

Looking through the source , it looks like you are using the aggregate() function, the pipeline is stored in the _pipeline property.

Using your example, if you are writing an aggregation pipeline like this ...

 var myAggregation = Model // "Model" should actually be the name of your model .aggregate() .match({ value: { $gt: 1000 } }) .match({ category: { $in: [1, 2, 3] } }) .sort('-date') .skip(100) .limit(10); 

Then myAggregation._pipeline will look like this:

 [ { '$match': { value: { $gt: 1000 } } }, { '$match': { category: { $in: [1, 2, 3] } } }, { '$sort': { date: -1 } }, { '$skip': 100 }, { '$limit': 10 } ] 

However, I noticed that you are using the where() function, which actually creates Query in the mongoose instead of the aggregation pipeline. If you use where() , the conditions and parameters are set somewhat differently. Instead of myAggregation._pipeline they will be split into myAggregation._conditions and myAggregation.options . They are not written in exactly the same way, but maybe you can do some kind of conversion to the desired format.

0
source

Source: https://habr.com/ru/post/1486291/


All Articles