Home > database >  How to execute a function in MongoDB Shell?
How to execute a function in MongoDB Shell?

Time:09-29

I have a MongoDB function to Insert some data from 1 Doc to another Doc as below, I don't know if it's right or wrong but now I just want to find a way to test it on MongoDB Shell.

function loadEducation() {
        const bulkInsert = db.education.initializeUnorderedBulkOp();
        const documents = db.summaryData.find({});

        documents.forEach(function (doc) {
            const element = {
                education: "$doc.education", 
                "education_num": "$doc.education_num"
            };
            bulkInsert.find(element).upsert().replaceOne(element);
        });
        bulkInsert.execute();
        return true;
        }

I've read many posts on the internet but non of them work. For example:

  1. I've already insert the function into db.system.js, but I can't use db.loadServerScripts() because the error "db.loadServerScripts is not a function"

  2. db.eval("loadEducation()") won't work too. The same error as above "db.eval is not a function"

There are many posts about this kind of problem on the internet (StackOverflow too) but there is no answer at all. For example here and here and here

CodePudding user response:

There is no need to store the definition of this function into the server itself, and there are a variety of ways to test it. For both of the two demonstrated below I will be using the MongoDB Shell (which is the newer utility that replaces the previous mongo interface).

The first option is simply to open the shell session and paste the function in:

$ ./mongosh
...
> loadEducation
ReferenceError: loadEducation is not defined
test> function loadEducation() {
...         const bulkInsert = db.education.initializeUnorderedBulkOp();
            ...
...         }
[Function: loadEducation]
> loadEducation
[Function: loadEducation]
>

The second option involves saving the function definition to a file. Here I've done so using a file named customFile that is saved in the current directory that my command line is in. Namely:

$ cat customFile
function loadEducation() {
        const bulkInsert = db.education.initializeUnorderedBulkOp();
        const documents = db.summaryData.find({});

        documents.forEach(function (doc) {
            const element = {
                education: "$doc.education",
                "education_num": "$doc.education_num"
            };
            bulkInsert.find(element).upsert().replaceOne(element);
        });
        bulkInsert.execute();
        return true;
        }
$

The second option then is to open the shell and then use the load() method:

$ ./mongosh
...
> loadEducation
ReferenceError: loadEducation is not defined
> load('customFile')
true
> loadEducation
[Function: loadEducation]
>

At this point for both options you can then simply call the function using loadEducation() in the shell session as expected.

  • Related