How to store MongoDB aggregation pipelines in the database as document?

Hi, I try to store MongoDB aggregation pipeline in the database as document to read it later from nodejs applecation. Worked solution - convert aggreagate to hex, save in the mongodb document and convert back from hex by JSON.parse

[
        {
            "$match": {
                "infoCurrent.factoryNumber": "11868424"
            }
        }, 
        {
            "$limit": 50.0
        }
    ]

5b0a20202020202020207b0a20202020202020202020202022246d61746368223a207b0a2020202020202020202020202020202022696e666f43757272656e742e666163746f72794e756d626572223a20223131383638343234220a2020202020202020202020207d0a20202020202020207d2c200a20202020202020207b0a20202020202020202020202022246c696d6974223a2035302e300a20202020202020207d0a202020205d

May be there is another way to store, to view aggregate pipeline in document as JSON, not hex

What was wrong with the above?

It seems to work fine in the current version of an M0 cluster.

original_pipeline = [
        {
            "$match": {
                "infoCurrent.factoryNumber": "11868424"
            }
        }, 
        {
            "$limit": 50.0
        }
    ]

c = db.aggregations

c.insertOne( { _id : 0 , pipeline : original_pipeline } )

c.findOne()

> { _id: 0,
  pipeline: 
   [ { '$match': { 'infoCurrent.factoryNumber': '11868424' } },
     { '$limit': 50 } ] }

stored_pipeline = c.findOne( { _id:0 } ).pipeline

c.aggregate( stored_pipeline ) 
2 Likes

Interesting, I’d just suggest a view for most cases though.

Storing a workspace of queries in a central location could be a great use for this.

2 Likes

Unfortunatly restriction applies to embedded pipelines, such as pipelines used in $lookup or $facet stages.

1 Like

Thanks, good idea!
I tried to create a document with original_pipeline through the 3Tstudio, but it gave an error
Usiong insertOne and from compas - all OK!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.