MongoDB

Basic MongoDB Commands

Starting and Stopping the MongoDB Server

  • Starting MongoDB:
    • Windows: Run mongod in Command Prompt. If installed as a service, it might start automatically.
    • macOS/Linux: Run mongod in Terminal.
  • Stopping MongoDB:
    • Windows: Press Ctrl+C in the Command Prompt where mongod is running.
    • macOS/Linux: Press Ctrl+C in the Terminal where mongod is running. Alternatively, use sudo systemctl stop mongod for system service.

Basic MongoDB Shell Commands (mongo)

  • Connecting to MongoDB Shell:
    • Run mongo in Command Prompt or Terminal to start the MongoDB shell.
  • Basic Commands:
    • Show Databases: show dbs
      • Example: > show dbs
    • Use a Database: use <dbName>
      • Example: > use myDatabase
    • Create a Collection: This happens implicitly when inserting documents.
    • Show Collections: show collections
      • Example: > show collections

Insert a Document:

> db.myCollection.insertOne({ name: "John", age: 30 })

Find Documents:

> db.myCollection.find()

Update a Document:

> db.myCollection.updateOne({ name: "John" }, { $set: { age: 31 } })

Delete a Document:

> db.myCollection.deleteOne({ name: "John" })

Leave a Reply

Your email address will not be published. Required fields are marked *