Inserting an Array Inside an Object with MongoDB's $push Operator

06 May 2023 Balmiki Mandal 0 Core Java

Insert Array Inside an Object in MongoDB

MongoDB is a popular NoSQL database used by developers all over the world. One of its most powerful features is the ability to store arrays inside objects. Arrays inside objects are useful when you have a set of values that you want to store together. For example, if you need to store a list of names and ages, you could use an array inside an object.

To insert an array inside an object in MongoDB, you need to first create a document. You can do this by using the db.collection.insert() method. For example, here's how you would insert an object with an array inside it into a collection called "users":

db.users.insert({
  name: "John Doe",
  age: 35,
  hobbies: ["reading", "swimming", "hiking"]
});

This will create a document with an object that contains the properties name, age, and hobbies. The hobbies property is an array containing three strings.

You can also update an existing document and add an array inside an object. This is done using the db.collection.update() method. For example, here's how you would add a new hobby to the array in the previous example:

db.users.update(
  {name: "John Doe"},
  {$push: {hobbies: "biking"}}
);

This will add the string "biking" to the hobbies array. You can also use the $pull operator to remove an item from the array, or the $set operator to replace the entire array.

In summary, MongoDB offers a powerful way to store arrays inside objects. This is useful when you need to store a set of related values in a single object. To insert an array into an object, you can use the db.collection.insert() or db.collection.update() methods.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.