Mongodb
Mongodb
Mongodb
Syntax
Show Databases
Drop Database
This will delete the selected database. If you have not selected any database, then it
will delete default 'test' database.
Example
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
The createCollection() Method
Syntax
db.createCollection(name, options)
Example
db.post.insertOne([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
}
])
Insertion of Many Records:
To insert many records into MongoDB collection, you need to use MongoDB's insertMany()
Syntax
>db.collection_name.insertMany(document1 , document2, … )
Example
db.post.insertMany([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
}, {
title: Php Overview',
description: ‘Php is server scripting language',
tags: [‘php', ‘server'],
likes: 70
},
])
Deletion of One Record
To delete data into MongoDB collection, you need to use MongoDB’s deleteOne() or
deleteMany()
Syntax
>db.collection_name.deleteOne(condition)
Example
Syntax
> db.collection_name.deleteMany(condition)
Example
db.post.deleteMany({})
Syntax
>db.collection_name.updateOne(condition , set)
Example
db.post.updateOne([
{
title: 'MongoDB Overview’,
},
{
$set : { likes : 200 }
}
]);
Updation of Many Records:
To update many documents into MongoDB collection, you need to use MongoDB’s
updateMany()
Syntax
>db.collection_name.updateMany(condition , set)
Example
db.post.updateMany([
{
title: 'MongoDB’,
},
{
$set : { likes : 200 }
}
]);
The find() Method : Query Data
To query data from MongoDB collection, you need to use MongoDB's find() method.
Syntax
>db.collection_name.find()
find() method will display all the documents in a non-structured way.
Eg: db.post.find({likes : 100});
Syntax
>db.mycol.find().pretty()
examples
• db.coll.find({"year": {$gt: 1970}})
• db.coll.find({"year": {$gte: 1970}})
• db.coll.find({"year": {$lt: 1970}})
• db.coll.find({"year": {$lte: 1970}})
• db.coll.find({name: {$exists: true}})
• db.coll.find({name: /^Max/})
• db.coll.find({}).sort({"year": 1, "rating": -1})
AND in MongoDB
In the find() method, if you pass multiple keys by separating them by ',' then
MongoDB treats it as AND condition.
Syntax
>db.mycol.find(
{
$and: [
{key1: value1}, {key2:value2}
]
}
).pretty()
OR in MongoDB
To query documents based on the OR condition, you need to use $or keyword.
syntax of OR −
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()