So, As you all may know unlike any other conventional DB, MongoDB allows us to store collections like arrays and provides us with multiple functionalities to work with them, So In this blog, we will take a look at how we can work with arrays in MongoDB.
So let’s understand this using an example,
db.students.insertMany([ { "_id": 1, "name":"Ram", "age": 24 "hobbies": ["cricket", "tennis"] }, { "_id": 2, "name":"Rahul", "age":20, "hobbies": ["cricket"] }, { "_id": 3, "name":"Riya", "age":23, "hobbies": ["FootBall", "tennis"] } ]) So here we have inserted documents about the general information of a student and his or her hobbies.
There are some major operators that are provided to us to work with Arrays –
Pop
The $pop operator removes the first or last element of an array. Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array.
{ $pop: { : <-1 | 1>, ... } }
db.students.update( { _id: 1 }, { $pop: { hobbies: -1 } } )
This will remove cricket from hobbies of Ram, as cricket was the first element of the array, Similarly, if we would have used “1” it would have removed the last element from the array so in our case tennis.
Pull
The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
{ $pull: { : <value|condition>, : <value|condition>, ... } }
db.students.update( { _id: 3 }, { $pull: { hobbies: { $in: ["football"] }} } )
This will remove football from hobbies of Riya
Push
The $push operator appends a specified value to an array.
{ $push: { <field1>: <value1>, ... } }
db.students.update( { _id: 3 }, { $push: { hobbies: "cricket" } } )
This will add cricket to hobbies of Riya.
PullAll
The $pullAll operator removes all instances of the specified values from an existing array. Unlike the $pull operator that removes elements by specifying a query, $pullAll removes elements that match the listed values.
{ $pullAll: { <field1>: [ <value1>, <value2> ... ], ... } }
db.students.update( { _id: 3 }, { $pushAll: { hobbies: ["cricket"] } } )
This will remove cricket from hobbies of Riya, even if it occurs multiple times in the hobbies, all of the values of cricket will be removed.
There are many more operators provided by MongoDB, Hopefully, this blog introduced you with some.
