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"]})
Adding Multiple Elements
$push - can be used to add more elements to an array.
db.products.findOneAndUpdate({"name":"Elon Musk"}, {$push:{"children": "payPal"}})
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}})
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}}})
$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"}})
Thank you, Please follow me
Top comments (1)
Hello ! Don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code 😎