show dbs
use database name
db.dropDatabase()
use database name
db
db.createCollection('collection name')
show collections
db.name.insert({
name:'mario',
address:'paragraph',
city:'toronto',
age:3,
tags:['cricket','football'],
user:{
name:'mario',
status:'author',
},
date: Date()
})
db.name.insertMany([
{
name:'max',
address:'paragraph',
city:'toronto',
age:30,
tags:['cricket','football'],
date: Date()
},
{
name:'jonas',
address:'paragraph',
city:'toronto',
age:27,
tags:['cricket','football'],
date: Date()
},
{
name:'angela',
address:'paragraph',
city:'toronto',
age:25,
tags:['barbies','soccer'],
date: Date()
}
])
db.name.find()
/*formatted output*/
db.name.find().pretty()
db.name.find({age:25})
//return the collection match with condition
db.info.find().sort({age:1})
db.info.find().sort({age:-1})
db.info.find({tags:"cricket"}).count()
//returns number count
db.info.find().limit(2)
//limit the search results counts
db.name.find().sort({age:-1}).limit(2)
db.name.find().forEach(function(doc){print('blog post:'+doc.name)})
db.info.findOne({name:"max"})
db.info.update({name:"max"},
{
"name" : "maximilian",
"address" : "new Germany",
"city" : "",
"age" : 35,
"tags" : [
"swimming",
"football"
],
date: Date()
},{
upsert:true
})
//upsert - if no row found it will create new one , that it is like update and also insert
db.name.update({name:'jonas'},{
$set:{
city:"Romania",
age:56
}
})
$set : updates only specific fields but keep others
db.name.update({name:'mario'},{
$inc:{age:30}
})
db.name.update({name:'mario'},{
$rename:{age:"year"}
})
db.info.remove({name:'maximilian'})
db.name.update({name:'jonas'},{
$set:{
comments:[
{
user:'yoshi',
desc:'colleague',
date:Date()
},
{
user:'chun-li',
desc:'colleague',
date:Date()
}
]
}
})
//Update of a document but actually just an insert/append of a sub-document
db.name.find({
comments:{
$elemMatch:{
user:'yoshi'
}
}
})
db.name.createIndex({name:'text'})
db.name.find({
$text:{
$search:"\"Post T\""
}
})
Greater than
db.name.find({year:{$gt:3}})
Greater than equal to
db.name.find({year:{$gte:3}})
Les than
db.name.find({year:{$lt:3}})
Less than equal to
db.name.find({year:{$lte:3}})