Creating Data

In MongoDB, you can create data using the insertOne() and insertMany() methods. These methods allow you to add new documents to a collection.

Inserting a Single Document

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.

Inserting Multiple Documents

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.

Reading Data

In MongoDB, you can read data using the find() and findOne() methods. These methods allow you to retrieve documents from a collection.

Retrieving All Documents

To retrieve all documents in a collection, use the find() method:

use database
db.<collection_name>.find()