MongoDB $Map Operator
admin 40.00 KiB
config 112.00 KiB
local 72.00 KiB
Use the “test” database to start adding some data into a MongoDB database, i.e. “use test”.
already on the db test
Example 1:
Here is an example of using the $map operator to square each element of an array in a collection. We generate a new collection named “Info” in MongoDB’s “test” database by casting off the createCollection function of MongoDB. The createCollection() method returns an object with the “ok” property and a value of 1 which indicates that the collection is successfully created.
{ ok: 1 }
After the collection is generated, we insert some array-type records in it. Therefore, the insertMany function is cast off here to add three records, each containing the “Arr” field of an array type with some numerical values.
{ acknowledged: true,
insertedIds: {
'0': ObjectId("63c4d968ac8011ecc27d7a35"),
'1': ObjectId("63c4d968ac8011ecc27d7a36"),
'2': ObjectId("63c4d968ac8011ecc27d7a37")
} }
After the successful insertion of records into the “Info” collection, you can take a look at it using the “find” function as we used in the following-attached query:
[
{ _id: ObjectId("63c4d968ac8011ecc27d7a35"), id: 1, Arr: [ 2, 4, 6 ]},
{ _id: ObjectId("63c4d968ac8011ecc27d7a36"), id: 2, Arr: [ 3, 5, 7 ] },
{ _id: ObjectId("63c4d968ac8011ecc27d7a37"), id: 3, Arr: [] }
]
In this example, the map operator is used to add each element in the “Arr” array for the document for all the three records. The input for the map operator is set to “$Arr” which references the “Arr” array in the documents of the “Info” collection. The “as” parameter is set to “n” which is used as a placeholder for each element in the array within the function. The “in” parameter contains the function which, in this case, is the $add operator that updates each element of an “Arr” array by adding 1. The output of this operation is a new array with the updated number of elements, but each element is the sum of the original element and “1” as displayed in the following output:
[
{ _id: ObjectId("63c4d968ac8011ecc27d7a35"), A: [ 3, 5, 7 ] },
{ _id: ObjectId("63c4d968ac8011ecc27d7a36"), A: [ 4, 6, 8 ] },
{ _id: ObjectId("63c4d968ac8011ecc27d7a37"), A: [] }
]}
Example 2:
Let’s have another example of utilizing the “map” operator of MongoDB. Starting with this illustration, you should create a new collection named “Info” in your test database. The createCollection() method is used to create a new collection in the current database which is “test”. Since we already created it through the “createCollection” method of the database, we skip that step here.
The following query uses the MongoDB command line interface (CLI) to insert multiple documents into a collection called “Data”. Each document represents a city and its distance in miles to the other locations. The command uses the insertMany() method to insert the three documents at once. Each document has a “city” field with a string value and a “distance” field with an array of numbers. The insertMany() method returns an object with the “acknowledged” and “insertedIds” properties which confirms that the operation is successful and provides the unique ObjectIds which is assigned to each inserted document.
... { "city": "London", "distance": [77.76, 14.72, 11.56]},
... { "city": "Texas", "distance": [44.70, 64.99, 94.6]} ])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("63c4e24cac8011ecc27d7a38"),
'1': ObjectId("63c4e24cac8011ecc27d7a39"),
'2': ObjectId("63c4e24cac8011ecc27d7a3a")
} }
This query is used to retrieve all documents from a collection called “Data”. The find() method is used with an empty query {}, which means that it returns all documents in the collection. The output is an array of documents that matches the query where each document has an “_id” field which is a unique ObjectId assigned to it, a “city” field with a string value, and a “distance” field with an array of numbers. This query shows all the documents that were inserted.
[
{ _id: ObjectId("63c4e24cac8011ecc27d7a38"), city: 'Newyork', distance: [ 22.56, 66.7, 88.1 ] },
{_id: ObjectId("63c4e24cac8011ecc27d7a39"), city: 'London', distance: [ 77.76, 14.72, 11.56 ] },
{ _id: ObjectId("63c4e24cac8011ecc27d7a3a"), city: 'Texas', distance: [ 44.7, 64.99, 94.6 ] }
]
The following query uses the MongoDB “test” database to perform an aggregate operation on the “Data” collection. The aggregate() method is used with an array that contains a single pipeline stage which is the $project stage. The $project stage is used to reshape the documents in the collection by specifying a new set of fields. In this case, the city field is passed through and a new field, “Adj”, is added. The new field “Adj” is created using the $map operator which applies a specified expression to each element of an input array and returns an output array with the same number of elements.
The $map operator takes three arguments: the input array which is “$distance”, a variable name for the current element in the input array which is “dc”, and an expression that is applied to each element of the input array. In this case, the expression is to truncate the decimal value of the distance using the $trunc operator. The result is an array of documents with the same structure as the original documents, but with an additional “Adj” field that contains an array of integers which are truncated from the “distance” field.
... $map: { input: "$distance", as: "dc", in: { $trunc: "$$dc" } } }}} ])
[
{ _id: ObjectId("63c4e24cac8011ecc27d7a38"), city: 'Newyork', Adj: [ 22, 66, 88 ] },
{ _id: ObjectId("63c4e24cac8011ecc27d7a39"), city: 'London', Adj: [ 77, 14, 11 ] },
{ _id: ObjectId("63c4e24cac8011ecc27d7a3a"), city: 'Texas', Adj: [ 44, 64, 94 ] }
]
Conclusion
This guide elaborates on the use of the “map” operator in MongoDB very clearly in its introduction. To support the explanation that we provided in the introduction, we explained two related examples in this article. Going through these examples, you can add a value to an array element of a particular document and can truncate the decimal points from specific array elements. In conclusion, MongoDB’s $map operator is a powerful feature that allows the developers to transform the arrays of documents in a collection. It’s easy to use and can be used in combination with the other aggregation operators to perform more complex transformations. With $map, the developers can easily manipulate the data and make it more useful for their applications.
Source: linuxhint.com