MongoDB save aggregation result and retrieve saved result

Viewed 715

My mongo version is 3.4

I'm running a complex aggregation and writing the result to a collection using $out stage.

What I wish to do is, if that aggregation is ran before and result exists on target collection, just return the saved result without rerunning the whole pipeline.

Problem 1 is, when $out is used, aggregation doesn't return any results, so I have to send a separate query to the target collection to retrieve them.

Problem 2 is, I need another query to check if aggregation is ran before.

Is it possible to combine all 3 queries to a single pipeline, so it would:

  1. check outCollection, if result with given user_id exists, return it
  2. if doesn't, run pipeline and save the result to outCollection
  3. return aggregation result

my current pipeline looks like:

db.getCollection('sourceCollection').aggregate([
    {
        $match: {
            user_id: "myUserId"
        }
    },...//perform various steps
    {
        $out: "outCollection"
    }],{
    allowDiskUse: true
})

Result is saved to outCollection in a document like:

{ user_id: "myUserId", aggResult: [...] }
0 Answers
Related