MongoDb Basics
MongoDB is
- an open-source document database .
- leading No SQL database.
- written in C++.
Basic Commands and Queries
1. MongoDB use DATABASE_NAME is used to create database.
use DATABASE_NAME
If you want to create a database with name <mydb>, then use DATABASE statement
>use mydb
switched to db mydb
2.To check your currently selected database, use the command db
>db
mydb
3.If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
4.The insert() Method
>db.COLLECTION_NAME.insert(document)
Insert a single document
db.collection_name_here.insert({});
Example : -
db.collection_name_here.insert({
"name" : "your name",
"age" : 22
})
Insert multiple documents at the same time
db.collection_name_here.insert([{},{},{},{}])
Example : -
db.collection_name_here.insert([{"name" : "sanduni", "age" : 23},{"name" : "hiruni", "age" : 23},{"name" : "nimasha", "age" : 27},{"name" : "lochana", "age" : 22}])
Note the syntax difference between inserting a single document and multiple documents
5.The Find method
To query data from MongoDB collection, you need to use MongoDB's find() method.
find() method will display all the documents in a non-structured way.
6.The pretty() Method
To display the results in a formatted way, you can use pretty() method.
>db.mycol.find().pretty()
Apart from find() method, there is findOne() method, that returns only one document.