Advantages and disadvantages of Stored Procedure equivalents

Hi @John_Page,

Thank you for your detailed answer! You and @MaBeuLux88_xxx are the best! You two threads will become the reference for people googling “MonoDB stored procedures” :slight_smile:

Can I ask two clarifications which I believe could benefit the community? I will reference a concrete example below, one of my MongoDB Server-side functions (it does a simple aggregation whereby it “joins” data from two collections):

  • I am not sure I understand what you mean when you say MongoDB Server-side functions “cannot run aggregations”. I can call my function getUser("john.doe@unknown.com"), either from my mongo shell or from Node. Are you referring to other types of aggregations that cannot run?
  • When you say “the client code retrieves them and runs them” are you referring to MongoDB Server-side functions stored in system.js? Or are you referring to storing aggregation pipelines code e.g. in a non-system collection? When you say that the “client code […] runs them”, could the “client” (from the perspective of MongoDB) in fact be a node server (from the perspective of the web app)?
// collection: system.js
{
   "_id" : "getUser",
   "value" : Code("
      function (emailAddress) {\n
         return db.users.aggregate([\n
            { $match: { email: emailAddress } },\n
            {\n
                $lookup: {\n
                    from: \"activitiesbuckets\",\n
                    localField: \"_id\",\n
                    foreignField: \"user\",\n
                    as: \"activities\"\n
                }\n
            }\n
        ]);\n
    }
")
}
1 Like