In MongoDB, data is stored in the form of documents (JSON-like objects). These documents are organised within collections, and collections are stored within a database.
MongoDB provides two main methods to insert data into a collection:
- insertOne()
- insertMany()
insertOne()
insertOne() is used to insert one document into the collection.
use myDatabase db.students.insertOne({ name: "Anuj Kumar", age: 25, city: "Delhi", skills: ["PHP", "Python", "MongoDB"] })
If the students collection does not exist, MongoDB will create it automatically when you insert the first document.
insertMany()
insertMany() is used to insert more than one document into the collection.
db.students.insertMany([ { name: "Amit", age: 30, city: "Mumbai" }, { name: "Riya", age: 28, city: "Bangalore" }, { name: "Karan", age: 35, city: "Chennai" } ])
Show all documents in a collection:
db.students.find()
Note:Each document automatically gets a unique
_id
field if not provided.
The post MongoDB Insert Document in Collection appeared first on PHPGurukul.
Source: Read MoreÂ