Loading

MongoDB commands and methods

MongoDB commands and methods

Hi Friends In this article I will try to cover all basic mongodb commands and Methods. So Lets Start.

use :- MongoDb create a databse by this command if database is not exists else return the existing database.

Syntax

use condinghub-database

db :- This is commad is to check the selected database.

Syntax

db

show dbs :- This command will display the all mongoDB databse.

Syntax

show dbs

db.dropDatabase() :-This method will delete the selected databse.

Syntax

db.dropDatabase()

db.createCollection(name, options) :- This method create a new collection. Option parameter is optional

Syntax

db.createCollection("products")

insert() :- In mongoDB you don't need to create a collection to insert the data if collection is not created & you run the insert command it will create a collection to then insert the data to newly created collection isn't this is cool !

Syntax

db.COLLECTION_NAME.insert(document)

db.products.insert({"name": "Camera"})

db.products.insert([ {"name": "Camera"}, {"name": "Mobile"}])

drop() :- This method is used to drop a collection from the database.

Syntax

db.COLLECTION_NAME.drop()
db.products.drop()

insertOne() :- This method insert single data into collection

Syntax

db.COLLECTION_NAME.insertOne(document)
db.products.insertOne({"name": "Camera"})

insertMany() :- This method insert bulk data into the collection

Syntax

db.COLLECTION_NAME.insertMany([])

db.insertMany([ {"name": "Camera"}, {"name": "Mobile"}])

find() :- This method is used to query the data from mongoDB

Syntax

db.COLLECTION_NAME.find(

findOne() :- This method will query the document and return only one result.

Syntax

db.COLLECTION_NAME.findOne()

db.products.findeOne({"name": "Camera"})

pretty() :- This method display the results in properly formated.

Syntax

db. COLLECTION_NAME.find().pretty()

update() :- This method update the mongoDB collection data.

Syntax

db.products.update({'name':'Camera'},{$set:{'name':'Digital Camera'}})

remove() :- This method remove the collection data.

Syntax

db.COLLECTION_NAME.remove(CONDITION)

db.products.remove({'name':'Digital Camera'})

limit() :- This method is used to query the data with limit option.

Syntax

db.COLLECTION_NAME.find().limit(number)

db.products.find().limit(1)

skip() :- This method is used to query the data with limit & skip option so we can skip the data. Syntax

db.COLLECTION_NAME.find().limit(number).skip(number)

db.products.find().limit(1).skip(1)

Conclusion

This is a simple post about MongoDB commands & method. I hope you like this article.

You May Like: Handle asynchronous calls using callback vs promise vs async-await

Related Articles