show dbs
db
cls
use acme
db.dropDatabase()
db.createCollection('posts')
show collections
db.buzzwords.insertOne({word:'wow'})
db.posts.insertOne({
title: 'Post One',
body: 'Body of post one',
category: 'News',
tags: ['news', 'events'],
user: {
name: 'John Doe',
status: 'author'
},
date: Date()
})
db.posts.insertMany([
{
title: 'Post Two',
body: 'Body of post two',
category: 'Technology',
date: Date()
},
{
title: 'Post Three',
body: 'Body of post three',
category: 'News',
date: Date()
},
{
title: 'Post Four',
body: 'Body of post three',
category: 'Entertainment',
date: Date()
}
])
db.posts.deleteOne({_id:ObjectId("6255bd2679f2ed82ecf46087")})
db.posts.find()
Less relevant in
Compass
, but relevant in other Mongosh clients.
db.posts.find().pretty()
db.posts.find({ category: 'News' })
db.posts.find({title: {$regex: '.*' + 'Three'}})
# asc
db.posts.find().sort({ title: 1 }).pretty()
# desc
db.posts.find().sort({ title: -1 }).pretty()
db.posts.find({ title: 'Post One' }, {
title: 1,
author: 1
})
you can also remove the _id which come by default :
db.posts.find({},{title:1, body:1, _id:0})
db.posts.find().count()
db.posts.find({ category: 'news' }).count()
db.posts.find().limit(2).pretty()
db.posts.find().limit(2).sort({ title: 1 }).pretty()
db.posts.find().forEach(function(doc) {
print("Blog Post: " + doc.title)
})
db.posts.find().forEach(x => print(x.title))
db.posts.findOne({ category: 'News' })
db.posts.updateOne({title:'Post Two'},{ $set: {title:'Post 2'}})
In the next example, because of the
upsert
option, so it will create the new object, even if there is not such document currently in the db.
db.posts.updateOne({ title: 'Post BZZ' },
{
$set: {
title: 'Post BZZ',
body: 'New body for post 333',
date: Date()
}
},
{
upsert: true
})
db.posts.updateOne({ title: 'Post Two' },
{
$inc: {
likes: 5
}
})
db.posts.updateOne({ title: 'Post Two' },
{
$rename: {
likes: 'views'
}
})
db.posts.updateOne({ title: 'Post One' },
{
$set: {
comments: [
{
body: 'Comment One',
user: 'Mary Williams',
date: Date()
},
{
body: 'Comment Two',
user: 'Harry White',
date: Date()
}
]
}
},
{ upsert: true}
)
From MongoDB Docs : The
$elemMatch
operator matches documents that contain an array field with at least one element that matches > all the specified query criteria.
db.posts.find({
comments: {
$elemMatch: {
user: 'Mary Williams'
}
}
}
)
db.posts.createIndex({ title: 'text' })
db.posts.find({
$text: {
$search: "\"Post O\""
}
})
db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })