MongoDB Shell command to read, create, delete and update Data
Please read official documentation and installation guide from MongoDB official site
show dbs;
use {your_database_name}
db;
db.createUser({
user: "sumon",
pwd: "sumon",
roles: ["readWrite"]
});
db.createCollection('customers');
// here db reffer the current database
show collections;
db.customers.insert({first_name: "Shafikul", last_name: "Islam", age: 26});
On relational database we can only add defined field value, But in nosql database we can add extra field {Not defined} & value as our wish
db.customers.insert([
{first_name: "Hridoy", last_name: "Khan", age: 21},
{first_name: "Simla", last_name: "Akter", age: 26, gender: "female"}
]);
db.customers.find();
// For more readable
db.customers.find().pretty();
db.customers.update({first_name: "shafikul"}, {first_name: "Shafikul", last_name: "Islam", age: 27, gender: "male"});
// First object for search the item and second object is data need to update
db.customers.update({first_name: "Hridoy"}, {
$set: {
gender: "Male"
}
});
db.customers.update({first_name: "Hridoy"}, {
$inc: {
age: 2
}
});
If we try update an item , but this is not there in collection, we can add if not exsist {Using additional option upsert}
db.customers.update({first_name: "Ethila"}, {
first_name: "Ethila",
last_name: "Akter",
age: 8
},
{
upsert: true
});
db.customers.update({first_name: "Ethila"}, {
$rename: {
"first_name": "nick_name"
}
});
db.customers.remove({first_name: "Shafikul"});
//If collection has multiple entry with name "Shafikul", But we want to delete one item. We can easily handle by add an additional option
db.customers.remove({first_name: "Shafikul"}, {justOne: true});
db.customers.remove({});
db.customers.find({$or:[{first_name: "Shafikul"},{first_name: "Hridoy"}]});
Find with greater then & less then & greater then or equal & less then or equal ($gt
& $lt
& $gte
& $lte
)
db.customers.find({ age: {$gt: 10} });
db.customers.find({ age: {$lt: 30} });
db.customers.find({ age: {$gte: 10} });
db.customers.find({ age: {$lte: 30} });
db.customers.find({"address.country": "Bangladesh"});
db.customers.find({"friends.name": "Shaun"});
db.customers.find().sort({first_name: 1});
// 1 means ascending order
// -1 for decending order
db.customers.find().sort({first_name: -1});
db.customers.find().count();
// count all entry
// count all entry where gender is male
db.customers.find({gender: "male"}).count();
db.customers.find().limit(4);
// return first 4 entry