Certainly! Below is the README content for your MongoDB cheatsheet repository:
A handy cheatsheet for MongoDB users to reference basic and advanced commands without the need to search for each command online.
-
Start MongoDB Shell:
mongo
-
View Databases:
show dbs
-
Switch Database:
use mydatabase
-
View Collections in Current Database:
show collections
-
Create Database:
use mydatabase
-
Create Collection:
db.createCollection("mycollection")
-
Insert Document into Collection:
db.mycollection.insertOne({ key: "value" })
-
Find Documents in Collection:
db.mycollection.find()
-
Update Document in Collection:
db.mycollection.updateOne({ key: "value" }, { $set: { key: "new value" } })
-
Remove Document from Collection:
db.mycollection.deleteOne({ key: "value" })
-
Drop Collection:
db.mycollection.drop()
-
Drop Database:
use mydatabase db.dropDatabase()
-
Index Management:
- Create Index:
db.mycollection.createIndex({ key: 1 })
- List Indexes:
db.mycollection.getIndexes()
- Drop Index:
db.mycollection.dropIndex("indexName")
- Create Index:
-
Aggregation Framework:
db.mycollection.aggregate([...])
-
Data Import and Export:
- Import Data from JSON:
mongoimport --db mydatabase --collection mycollection --file data.json
- Export Data to JSON:
mongoexport --db mydatabase --collection mycollection --out data.json
- Import Data from JSON:
-
User Management:
- Create User:
db.createUser({ user: "username", pwd: "password", roles: ["readWrite"] })
- List Users:
db.getUsers()
- Drop User:
db.dropUser("username")
- Create User:
-
Replica Sets and Sharding:
- Initialize Replica Set:
rs.initiate()
- Add Replica Set Member:
rs.add("hostname:port")
- Enable Sharding on Database:
sh.enableSharding("mydatabase")
- Shard Collection:
sh.shardCollection("mydatabase.mycollection", { shardKey: 1 })
- Initialize Replica Set:
-
Server Administration:
- Server Status:
db.serverStatus()
- Current Operations:
db.currentOp()
- Server Logs:
db.getLog("global")
- Server Status:
Feel free to copy and paste these commands into your MongoDB terminal for quick reference!
You can copy the content and save it into your README.md file in your MongoDB cheatsheet repository. This will provide users with an easy-to-access reference for MongoDB commands.