MongoDB

MongoDB Custom $function

MongoDB is a powerful and flexible document-oriented database that allows developers to store and retrieve data in a format that is similar to JSON. One of the most powerful features of MongoDB is its ability to use custom $functions to manipulate and query data. Custom server-side JavaScript methods, commonly referred to as “stored functions,” are supported by MongoDB and may be utilized in the query language and aggregate pipeline stages. These functions can be specified using the db.system.js collection and they can be used in queries or the aggregate pipeline by using the $function operator. In this article, we will take a look at some examples of custom $functions and the output that they produce.

Create Collection

Firstly, we will check the collection available in our database. Therefore, the MongoDB shell has been launched perfectly after connecting with its connection string. The “show collections” MongoDB instruction was executed to display all the collections we have. This command does not return anything on the shell because there are no collections in our “test” database as below. Therefore, we need to create a new collection first and then start working on it.

test> show collections

To add or create a new data collection in the MongoDB database, we must utilize the “db” instruction followed by the createCollection method. The createCollection method is specifically designed to create new collections taking the name of a collection to be created in its argument. In the instruction below, we have named the collection as “Test”. The output of the command returns the success status: 0 for failure and 1 for success. The command below returns 1 which means the command has been successful and the collection has been created.

test> db.createCollection("Test")

{ ok: 1 }

Insert Records

After adding a new collection to the database, it is necessary to add records to it because the collection might be empty at the time of creation. Therefore, after using the insertMany function of MongoDB in the “db” instruction, we have added 5 documents to the “Test” collection at once. The insertMany() function is specific for inserting multiple records at a time. All 5 records contain a total of 3 fields each: title, city, and area. The “title” field is of “string” type, the area field is of integer type and the city field is in the string-type array containing string elements. The output of this instruction shows the acknowledgment by showing the inserted IDs of each document separately assigned by the MongoDB database.

test> db.Test.insertMany([ {title: "USA", city: [ "Newyork", " Chicago", " Boston" ], area: 234567},

... {title: "UAE", city: [ "Dubai", " AbuDhabi", " Sharjah" ], area: 786907},

... {title: "Asia", city: [ "Bangkok", " Tokyo", " Beijing" ], area: 984567},

... {title: "Europe", city: [ "Italy", " Istanbul", " London" ], area: 1475997},

... {title: "Antarctica", city: [ "Villa Las Estrellas", " King Edward point", " Grytvkin" ], area: 2835997} ])

{

acknowledged: true,

insertedIds: {

'0': ObjectId("63cffd7d64f216739d14b251"),

'1': ObjectId("63cffd7d64f216739d14b252"),

'2': ObjectId("63cffd7d64f216739d14b253"),

'3': ObjectId("63cffd7d64f216739d14b254"),

'4': ObjectId("63cffd7d64f216739d14b255")

}}

Display Records

After the insertion of all the records in the “Test” collection of the “test” database of MongoDB, we are ready to have a look at all of them at once to verify the insertion. Thus, MongoDB’s “find” function can be cast off in the “db” instruction for this purpose. Make sure to use the name of a collection between the keyword “db” and the find() function. The parameters of the function “find” must contain the empty curly brackets without specifying any field name. The empty brackets consider fetching all the records from the collection with all the data fields while specifying one or more fields that leads to a single or only specified record display on the shell. Therefore, the output for this instruction, with the empty curly brackets in the find() function, displayed all 5 records of the “Test” collection each with all 3 fields: the title, the city, and the area. Also, every record can be identified separately from another using the “_id” field assigned by the MongoDB database.

test> db.Test.find({})

[

{ _id: ObjectId("63cffd7d64f216739d14b251"), title: 'USA', city: [ 'Newyork', ' Chicago', ' Boston' ], area: 234567 },

{ _id: ObjectId("63cffd7d64f216739d14b252"), title: 'UAE', city: [ 'Dubai', ' AbuDhabi', ' Sharjah' ], area: 786907 },

{ _id: ObjectId("63cffd7d64f216739d14b253"), title: 'Asia', city: [ 'Bangkok', ' Tokyo', ' Beijing' ], area: 984567 },

{ _id: ObjectId("63cffd7d64f216739d14b254"), title: 'Europe', city: [ 'Italy', ' Istanbul', ' London' ], area: 1475997 },

{ _id: ObjectId("63cffd7d64f216739d14b255"), title: 'Antarctica', city: [ 'Villa Las Estrellas ', ' King Edward point ', ' Grytvkin' ], area: 2835997 }

]

Example # 01:

Now that we are done with the insertion and display of the records from the “Test” collection, we are finally ready to apply the $function custom function to perform customizable operations on the fields. For example, you want to create a new runtime field in the collection “Test” that will contain details about the country, its cities, and the area it contains in a single sentence. For this, we need to utilize all three fields of the “Test” collection within the custom $function operator used in the “aggregate” function query shown below. The custom function takes all three fields of the “Test” collection in parameters to create a new field “Detail”. The return statement has been using these three fields to make a sentence and display it on the shell. It is necessary to specify the collection fields as “args” and the language set to “JS”. The output is showing a new runtime field “Detail” providing exact information in a sentence.

test> db.Test.aggregate([ {$addFields: {Detail: { $function: {body: function(title, city, area) { return `${title} has ${city} cities with ${area} area...` }, args: [ "$title", "$city", "$area"], lang:"js" } } }} ])

[

{ _id: ObjectId("63cffd7d64f216739d14b251"), title: 'USA', city: [ 'Newyork', ' Chicago', ' Boston' ], area: 234567, Detail: 'USA has Newyork, Chicago, Boston cities with 234567 area...' },

{ _id: ObjectId("63cffd7d64f216739d14b252"), title: 'UAE', city: [ 'Dubai', ' AbuDhabi', ' Sharjah' ], area: 786907, Detail: 'UAE has Dubai, AbuDhabi, Sharjah cities with 786907 area...' },

{ _id: ObjectId("63cffd7d64f216739d14b253"), title: 'Asia', city: [ 'Bangkok', ' Tokyo', ' Beijing' ], area: 984567, Detail: 'Asia has Bangkok, Tokyo, Beijing cities with 984567 area...' },

{ _id: ObjectId("63cffd7d64f216739d14b254"), title: 'Europe', city: [ 'Italy', ' Istanbul', ' London' ], area: 1475997, Detail: 'Europe has Italy, Istanbul, London cities with 1475997 area...' },

{ _id: ObjectId("63cffd7d64f216739d14b255"), title: 'Antarctica', city: [ 'Villa Las Estrellas ', ' King Edward point ', ' Grytvkin' ], area: 2835997, Detail: 'Antarctica has Villa Las Estrellas, King Edward Point, Grytvkin cities with 2835997 area...' }

]

Example # 02:

Let us take a look at another illustration to use the custom $function in MongoDB. Here, we are using the $addFields operator followed by the name of a field “AreaTripled” that we want to create using the $function operator. The custom function takes 1 field “area” as its argument and the “let” keyword allows us to declare a variable “triple” taking a value as “Area” field value multiplied by 3. The return statement will return and display the result calculated in the triple variable. Therefore, the output of the instruction attached below displays a total of 5 fields for each document of the Test field. The field “AreaTripled” has been generated by the use of a custom function showing the area for all the three cities listed in the “city” field of each document by multiplying the area field value by 3.

test> db.Test.aggregate([ {$addFields: {AreaTripled: { $function: {body: function(area) { let triple = area*3; return `${triple}` }, args: [ "$area"], lang:"js" } } }} ])

[

{ _id: ObjectId("63cffd7d64f216739d14b251"), title: 'USA', city: [ 'Newyork', ' Chicago', ' Boston' ], area: 234567, AreaTripled: '703701' },

{ _id: ObjectId("63cffd7d64f216739d14b252"), title: 'UAE', city: [ 'Dubai', ' AbuDhabi', ' Sharjah' ], area: 786907, AreaTripled: '2360721' },

{ _id: ObjectId("63cffd7d64f216739d14b253"), title: 'Asia', city: [ 'Bangkok', ' Tokyo', ' Beijing' ], area: 984567, AreaTripled: '2953701'},

{ _id: ObjectId("63cffd7d64f216739d14b254"), title: 'Europe', city: [ 'Italy', ' Istanbul', ' London' ], area: 1475997, AreaTripled: '4427991' },

{ _id: ObjectId("63cffd7d64f216739d14b255"), title: 'Antarctica', city: [ 'Villa Las Estrellas ', ' King Edward point ', ' Grytvkin' ], area: 2835997, AreaTripled: '8507991' }]

Conclusion

The article is on the custom functions in MongoDB and it demonstrates how a MongoDB environment is so powerful using such functions: as these functions allow the insertion of JSON-like data and its retrieval. After that, we created the collection and inserted records into it before using the custom $function operator. After setting the environment, we used two examples to illustrate the use of the custom $function. The examples covered the use of a custom $function operator to create a new data field with the help of already inserted fields of the collection and also perform calculations wherever possible via the use of variable declaration through the use of the “let” keyword.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.