In MongoDB, you can create data using the insertOne() and insertMany() methods. These methods allow you to add new documents to a collection.
Syntax:
db.<collection_name>.insertOne({})
Example:
use mydatabase
db.mycollection.insertOne({ name: "John Doe", age: 30 })
This method takes a single object as an argument, which represents the document to be inserted. The method returns an object with two properties: acknowledged and insertedId.
acknowledged: A boolean indicating whether the operation was successful.insertedId: The _id of the inserted document, or undefined if the operation failed.Syntax:
db.<collection_name>.insertMany([{}])
Example:
use mydatabase
db.mycollection.insertMany([
{ name: "Jane Doe", age: 25 },
{ name: "Bob Smith", age: 40 },
{ name: "Alice Johnson", age: 28 }
])
This method takes an array of objects as an argument, where each object represents a document to be inserted. The method returns an object with two properties: acknowledged and insertedIds.
acknowledged: A boolean indicating whether the operation was successful.insertedIds: An array of **_id**s of the inserted documents, or an empty array if the operation failed.In MongoDB, you can read data using the find() and findOne() methods. These methods allow you to retrieve documents from a collection.
To retrieve all documents in a collection, use the find() method:
use database
db.<collection_name>.find()