MongoDB Useful Commands

1) db.stats()
2) db.help()

Databases:
Create a new database: use name_of_db
Show all existing database: show dbs
Drop currently selected database: db.dropDatabase()
Insert in a database: db.name_of_db.insert(“name”:”abc”)

Collections:
To create a collection: db.createCollection(name, options)
In mongodb you don’t need to create collection. MongoDB creates collection automatically, when you insert some document.

Drop a collection: db.COLLECTION_NAME.drop()

Documents:
Insert Document:
we can insert a document with a insert or save command.
db.COLLECTION_NAME.insert(document)
db.COLLECTION_NAME.save(document)
If collection does not exist a new one is created.

Query Document: To query data from MongoDB collection, you need to use MongoDB’s find() method.
db.COLLECTION_NAME.find()

To get results in formatted way: db.mycol.find().pretty()
To get a single result in output file: db.mycol.findOne()

OR Query:
db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()

AND Query:
db.mycol.find({key1:value1, key2:value2}).pretty()


Update Document:
with update() and save() method
With update() method:
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

With save() method:
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

Remove Document:
db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Remove only one document:
db.COLLECTION_NAME.remove(DELETION_CRITERIA, 1)

Remove all documents:
db.COLLECTION_NAME.remove()

 

Query Projection:
db.COLLECTION_NAME.find({},{KEY:1})

 

Limit the records:
db.COLLECTION_NAME.find().limit(NUMBER)

Skip the documents:
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

 

Sort the documents: 1 is used for ascending order while -1 is used for descending order.
db.COLLECTION_NAME.find().sort({KEY:1})

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s