MongoDB Crash Course 2022 < TODO: Add Video Link
- Check
monosh
Version - Start the Mongo Shell
- Show Current Database
- Show All Databases
- Create Or Switch Database
- Drop Database
- Create Collection
- Show Collections
- Insert Document
- Insert Multiple Documents
- Find All Documents
- Find Documents with Query
- Sort Documents
- Count Documents
- Limit Documents
- Chaining
- Find One Document
- Update Document
- Update Document or Insert if not Found
- Increment Field (
$inc
) - Update Multiple Documents
- Rename Field
- Delete a Document
- Delete Multiple Documents
- Greater & Less Than
mongosh --version
mongosh "YOUR_CONNECTION_STRING" --username YOUR_USER_NAME
db
show dbs
use blog
db.dropDatabase()
db.createCollection('posts')
show collections
db.posts.insertOne({
title: 'Post 1',
body: 'Body of post.',
category: 'News',
likes: 1,
tags: ['news', 'events'],
date: Date()
})
db.posts.insertMany([
{
title: 'Post 2',
body: 'Body of post.',
category: 'Event',
likes: 2,
tags: ['news', 'events'],
date: Date()
},
{
title: 'Post 3',
body: 'Body of post.',
category: 'Tech',
likes: 3,
tags: ['news', 'events'],
date: Date()
},
{
title: 'Post 4',
body: 'Body of post.',
category: 'Event',
likes: 4,
tags: ['news', 'events'],
date: Date()
},
{
title: 'Post 5',
body: 'Body of post.',
category: 'News',
likes: 5,
tags: ['news', 'events'],
date: Date()
}
])
db.posts.find()
db.posts.find({ category: 'News' })
db.posts.find().sort({ title: 1 })
db.posts.find().sort({ title: -1 })
db.posts.find().count()
db.posts.find({ category: 'news' }).count()
db.posts.find().limit(2)
db.posts.find().limit(2).sort({ title: 1 })
db.posts.findOne({ likes: { $gt: 3 } })
db.posts.updateOne({ title: 'Post 1' },
{
$set: {
category: 'Tech'
}
})
db.posts.updateOne({ title: 'Post 6' },
{
$set: {
title: 'Post 6',
body: 'Body of post.',
category: 'News'
}
},
{
upsert: true
})
db.posts.updateOne({ title: 'Post 1' },
{
$inc: {
likes: 2
}
})
db.posts.updateMany({}, {
$inc: {
likes: 1
}
})
db.posts.updateOne({ title: 'Post 2' },
{
$rename: {
likes: 'views'
}
})
db.posts.deleteOne({ title: 'Post 6' })
db.posts.deleteMany({ category: 'Tech' })
db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })
thanks