12 basic MongoDB commands
What is MongoDB Database?
MongoDB is a source-available, cross-platform, document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas. (Wikipedia)
MongoDB is not an SQL-based database. In MongoDB, tables are referred to as Collections, and Records are referred to as Documents.
12 MongoDB commands you should know
Below, we discuss some useful MongoDB shell commands.
1. How to show the databases present
show dbs
2. How to create a database
use [name of database]
Example
use users
3. How to check active collection or database
db
4. How to create a collection
db.createCollection("[name of collection]")
Example
db.createCollection("customer")
5. How to show collections
show collections
6. How to insert a document into a collection
db.[name of collection].insert({})
Example
db.customer.insert({"name": "Theodore", "gender": "M"})
Or, put the documents in an array to insert more than one document:
db.customer.insert([
{"name": "Theodore", "gender": "M"},
{"name": "Jane Doe", "gender": "F"},
{"name", "John Doe", "gender": "M"}
])
7. How to show all documents in a collection
db.[collection Name].find()
or
db.[collection name].find().pretty()for a well indented list.
Example
db.customer.find().pretty()
8. How to limit fields when listing all the documents present in a collection
Example
db.customer.find({},{id:1}).pretty()
The above will only display _id the result.
9. How to update a document with $set
db.[name of collection].update({},{$set: {}})
Example
db.customer.update(
{"name":"Theodore"},
{$set:
{"name": "Theodore Kelechukwu Onyejiaku"}
}
)
10. How to rename a field in a document with $rename
Example
db.customer.update(
{"name": "Theodore Kelechukwu Onyejiaku"},
{$rename:
{"gender":"sex"}
}
)
11. How to delete or remove a field with $unset
Example
db.customer.update(
{"name": "Theodore Kelechukwu Onyejiaku"},
{$unset:
{"sex": 1}
}
)
12. How to remove a document from a collection
db.[name of collections].remove({})
or
db.[name of collections].remove({}, {justOne: true})to remove just one with the unique match.
Example
db.customer.remove({"name":"Jane Doe"})
Conclusion
We have gone over some of the basic and most frequently used MongoDB commands. Feel free to try them out, and of course, find some more advanced commands. Happy shelling!