Basic MongoDB Commands
- Starting MongoDB
mongo --host localhost:27017
2. Log Into mongoDB. <username> and <password> and <dbname> are all placeholder texts.
mongo -u <username> -p <password> --authenticationDatabase <dbname>
3. Show All databases
show dbs
4. Select the database you wish to work with. The "databaseName" is a placeholder referring to the database you want to use. If the database does not exist, MongoDB creates a new database with the provided name.
use databaseName
5. Authentication and Logging out of the database. "username" and "password" are placeholders for your username and password.
// Authenticate db.auth("username", "password");
// Logout db.logout()
6. List down Collections, users and roles
//list down collections showCollections db.getCollectionNames() //list users showUsers db.getUsers() //list available roles in db showRoles
7. create a collection. A collection is like a table in SQL. Note that MongoDB is NoSQL.
db.createCollection("collectionName");
8. Insert a document or data in the collection. You can insert one or many collections at a time.
(a) Inserting a single record. N.B <collectionName> is a placeholder for the name of the collection.
db.<collectionName>.insert({field1: "value", field2: "value"})
(b) Inserting Multiple records at once
db.<collectionName>.insertMany([{field1: "value1"}, {field1: "value2"}])
9. Save or update data in a collection. The command can also be used to insert a new record on the collection in case the ID did not exist.(save)
db.<collectionName>.save({"_id": new ObjectId("jhgsdjhgdsf"), field1: "value", field2: "value"});
10. Displaying collection records.
(a)display all records
db.<collectionName>.find();
(b) display only records based on the limit number e.g. 10
db.<collectionName>.find().limit(10);
(c) Display records based on the provided ID. You can also add other fields to narrow search parameters.
db.<collectionName>.find({"_id": ObjectId("someid")}, {field1: 1, field2: 1}); db.<collectionName>.find({"_id": ObjectId("someid")}, {field1: 0});
(d) Displays the number of records in a collection.
db.<collectionName>.count();
I have not yet covered all the commands. These are simple commands that are common in usage for MongoDB. The next piece will focus on adding more commands. Cheers!