DEV Community

Cover image for Array Manipulation in MongoDB
Ifeanyi Chima
Ifeanyi Chima

Posted on • Updated on

Array Manipulation in MongoDB

Arrays can be stored and manipulated in MongoDB. We are going to look at some operations that can be carried out on an array in MongoDB.

Firstly, we have to insert a record that has an array in our database.

db.products.insert({"name": "Elon Musk", "children": ["X Æ A-12", "Tesla", "Neuralink", "OpenAI", "spaceX", "Boring Co.", "Twitter"]})
Enter fullscreen mode Exit fullscreen mode

Adding Multiple Elements

$push - can be used to add more elements to an array.

db.products.findOneAndUpdate({"name":"Elon Musk"}, {$push:{"children": "payPal"}})
Enter fullscreen mode Exit fullscreen mode

Removing Multiple Elements

$pop - can be used to remove an element from an array. It removes one element at a time and can only be used with the values
1 (for the last element) or -1 (for the first element)

db.products.findOneAndUpdate({"name":"Elon Musk"}, {$pop: {"children":1}})
Enter fullscreen mode Exit fullscreen mode

Sorting

$sort modifier orders the elements of an array during a $push operation. To use the $sort modifier, it must appear with the $each modifier.
You can pass an empty array [] to the $each modifier such that only the $sort modifier has an effect.

db.products.findOneAndUpdate({"name":"Elon Musk"}, {$push:  {"children": {$each: [], $sort: 1}}})
Enter fullscreen mode Exit fullscreen mode

$addToSet, MongoDB provides a way to only allow unique elements into an array. An element will only be allowed into an array, if the element does not exist already.

db.products.updateOne({"name": "Elon Musk"}, {$addToSet: {"children": "Solar City"}}) 
Enter fullscreen mode Exit fullscreen mode

Thank you, Please follow me

Buy Me A Coffee

HTML GitHub

Top comments (1)

Collapse
 
thomasbnt profile image
Thomas Bnt ☕

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks