MongoDB is an open-source document-oriented NoSQL database that is designed to store a large scale of data and also allows you to work with that data very efficiently. It stores data in the form of JSON documents. MongoDB provides a SQL-like query language to query records based on the internal structure of the document itself. Document stores provide high flexibility and are often used for working with occasionally changing data.
In this post, I will mention a few MongoDB commands which are used more frequently by the developers.
- Database Operations
- Collections
- Create Documents
- Read Documents
- Update Documents
- Delete Documents
- Sorting
- Limit and Offset
- Add and Drop Index
- Range Queries
- Text Search
show dbs
db
use hashnode
db.dropDatabase()
show collections
db.createCollection('posts')
db.posts.insertOne(
{title: "blog post title", body: "blog post content"}
)
or
db.posts.insert(
{title: "blog post title", body: "blog post content"}
)
db.posts.insert( [
{title: "blog post 1 title", body: "blog post 1 content"},
{title: "blog post 2 title", body: "blog post 2 content"},
])
db.posts.findOne()
db.posts.find()
/* returns a cursor - show 20 results - "it" to display more */
db.posts.find().pretty()
/* returns a cursor - show 20 results - "it" to display more */
db.posts.find({'title' : 'blog 1 title'})
db.posts.updateOne({"_id": 1}, {$set: {"title": 'updated title'}})
/* update only specific fields */
db.posts.update({"category": "technology"}, {$set: {"category": 'computer science'}})
db.posts.update({ '_id' : 1 },
{
title: 'Post one',
body: 'New body for post 1',
},
{
upsert: true
})
db.posts.update({ "_id": 1 },
{
$inc: {
views: 5
}
})
db.posts.remove({ title: 'Post 1' })
# ascending order
db.posts.find().sort({ title: 1 }).pretty()
# descending order
db.posts.find().sort({ title: -1 }).pretty()
/* Skip 3 results*/
db.posts.find({}).skip(10)
/* Fetch only 3 results*/
db.posts.find({}).limit(3)
/* Sort by title , Skip first 10 results, fetch only next 3 documents*/
db.posts.find({}).sort({"title": 1}).skip(10).limit(3)
/* Create Index on single field */
db.posts.createIndex({"title": 1})
/* Create compound Index */
db.posts.createIndex({"title": 1, "date": 1})
db.posts. dropIndex("title_1")
/* find posts where views are greater than 50 */
db.posts.find({'views' : { '$gt' : 50 }})
/* find posts where views are greater than or equal to 50 */
db.posts.find({'views' : { '$gte' : 50 }})
/* find posts where views are less than 50 */
db.posts.find({'views' : { '$lt' : 50 }})
/* find posts where views are less than or equal to 50 */
db.posts.find({'views' : { '$lte' : 50 }})
db.posts.createIndex({content: "text"})
db.posts.find({
$content: {
$search: "post content"
}
})
Hope you find these resources useful. If you like what you read and want to see more about system design, microservices, and other technology-related stuff... You can follow me on
- Twitter here.
- Subscribe to my newsletter here.