[go: up one dir, main page]

0% found this document useful (0 votes)
39 views26 pages

NoSql Lab4

1) MongoDB allows schema validation through JSON Schema to ensure documents in a collection share a similar structure. 2) The mongoimport tool is used to import data from files like JSON, CSV into MongoDB collections. mongoexport exports data from MongoDB collections to file formats like JSON, CSV. 3) Roles like readWrite, dbAdmin are used to control access and privileges in MongoDB. The db.createUser() method is used to create users and assign roles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views26 pages

NoSql Lab4

1) MongoDB allows schema validation through JSON Schema to ensure documents in a collection share a similar structure. 2) The mongoimport tool is used to import data from files like JSON, CSV into MongoDB collections. mongoexport exports data from MongoDB collections to file formats like JSON, CSV. 3) Roles like readWrite, dbAdmin are used to control access and privileges in MongoDB. The db.createUser() method is used to create users and assign roles.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

PDPM-Indian Institute of Information Technology, Design and

Manufacturing
Jabalpur-482005, M.P., India

Mongodb Continuation.....

Subject Code: IT2C02


Subject Name: NoSQL Database
Instructor: Mr. Aditya Sharma
Schema Validation

• By default MongoDB has a flexible schema. This means that


there is no strict schema validation set up initially.

• Schema validation rules can be created in order to ensure that all


documents a collection share a similar structure.

• MongoDB supports JSON Schema validation. The $jsonSchema


operator allows us to define our document structure.
Schema Validation
db.createCollection("student”,
{validator: {
$jsonSchema: {
required: ["name", "roll_number"],
properties: {
name: {
bsonType: "string",
description: "Student name must be string - Required"
},
roll_number: {
bsonType: "int",
description: "Student roll number must be int - Required"
},
dob: {
bsonType: "date",
description: "Student DOB must be date - Optional"
},
marks: {
bsonType: “array” ,
description: "Student marks must be an array - Optional",
items.{ bsonType: “int”},
maxItems:5
}
}
}
}
Schema Validation

db.student.insertOne({name:"Std1",
roll_number:01})

db.student.insertOne({name:"Std2", dob:ISODate("2000-03-02"),
marks:[10,20,30]})

db.student.insertOne({name:"Std3", roll_number:xyz, dob:ISODate("2000-03-02"),


marks:[10,20,30]})

db.student.insertOne({name:"Std4", roll_number:23, dob:ISODate("20-06-2002"),


marks:[10,20,30]})

db.student.insertOne({name:"Std5", roll_number:20, dob:ISODate("2000-03-02"), marks:[”10",”20",”30"]})


Import data

• MongoDB provides a special tool that is used to import


data in the MongoDB and the tool is known as
mongoimport.

• Using this tool you are allowed to import the files like
JSON, CSV, or TSV in the MongoDB database.
Steps to Import data
• https://www.mongodb.com/try/download/database-tools ( Go to this link and download the zip
format of Mongodb Command Line Database Tools )

• Unzip it and go to the bin folder of the extracted folder

• Copy all the files present in the bin folder of the extracted folder to the Mongodb bin folder in
C:\Program Files\

• mongoimport --jsonArray --db database_name --collection collection_name --file


"C:\Users\Janvi\Desktop\file.json"

• mongoimport --db database_name --collection collection_name --type csv --file


"C:\Users\Janvi\Desktop\employee.csv" --headerline

• mongoimport --db database_name --collection collection_name --type csv --fields name,emp_id --file
"C:\Users\Janvi\Desktop\employee.csv"
Export data

• MongoDB allows you to export its data into other file


formats like JSON or CSV so that the data can be used
externally by other applications.

• Moreover, we can also use features like limit and sort on a


collection while exporting the data.
Steps to Export data
Note: mongoexport does not run in the mongo shell. So, when you use mongoexport
tool you have to exit from the mongo shell.

• mongoexport --db Database_name --collection student --out


"C:\Users\Janvi\Desktop\student.json"

• mongoexport --db Database_name --collection student --type=csv --fields


name,roll_number,dob --out "C:\Users\Janvi\Desktop\student.csv"

• mongoexport --db Database_name --collection student --type=csv --fields


name,roll_number --limit 2 --out "C:\Users\Janvi\Desktop\student.csv"
Create a user and add role
in Mongodb
db.createUser(user:”User_name”, pwd:”Your_password”, roles:[]);

• db.createUser( { user: "Admin", pwd: "admin123", roles:[ {role:"readWrite", db:"config"}, "clusterAdmin"]


} );

• db.createUser( {user: "janvi", pwd: "janvi123", roles:[ {role: "userAdmin" , db:"student"}] } ):

• db.createUser( {user: "janvi2", pwd: "one123", roles:[ ] } ):

• db.getUsers()

• mongo --username janvi --pasword janvi123 --authenticationDatabase student


• db.runCommand({connectionStatus: 1});
Different Built in Roles

• atlasAdmin • clusterMonitor
• readWriteAnyDatabas • hostManager
e • backup
• readAnyDatabase • restore
• read • userAdminAnyDatabase
• readWrite • dbAdminAnyDatabase
• dbAdmin • root
• dbOwner • __system
• userAdmin
• clusterAdmin
• clusterManager
https://www.mongodb.com/docs/manual/reference/built-in-roles/
MongoDB - Replication
Replication is the process of synchronizing data across multiple servers.

Purpose:
• Redundancy & increased data
availability.
Benefits:
• Protection against server loss.
• Enhanced redundancy.
• Improved data availability
• Mitigation of hardware failure.
• Overcoming service
interruptions.
.
MongoDB - Replication

Replica
Set
MongoDB - Sharding

Sharding means spreading data across many machines. It's how MongoDB
copes with more and more data.

Why Sharding?
• In replication, all writes go to master node
• Latency sensitive queries still go to master
• Single replica set has limitation of 12 nodes
• Memory can't be large enough when active dataset is big
• Local disk is not big enough
• Vertical scaling is too expensive
MongoDB - Sharding
MongoDB - Php
Step 1 : Search for Pecl Php Mongodb
MongoDB - Php
Step 2 : Go to the latest DLL file
MongoDB - Php
Step 3 : Download the Thread Safe(TS) file
MongoDB - Php
Step 4 : Unzip the downloded folder and copy the dll file
MongoDB - Php
Step 5 : Go to ext folder inside the php folder in xammp and paste the dll file
MongoDB - Php
Step 6 : extention=php_mongodb.dll
MongoDB - Php
Step 7 : Download and run Composer-Setup.exe file
MongoDB - Php
Step 8 : Make sure that the path is correct
MongoDB - Php
Step 9 : run composer require "mongodb/mongodb=^1.0.0" on terminal inside
your folder in htdocs

Step 10: Now Restart your xampp and you can start creating your files inside
the htdocs folder in xammp
MongoDB - Php
Creating connection:
Conn.php : // select a database
<?php $db = $conn->mydb;
require 'vendor/autoload.php';
echo "Database mydb
// connect to mongodb
selected";
$conn= new MongoDB\Client("mongodb://localhost:27017");
echo "Connection to database successfully";
?>
MongoDB - Php
Inserting a document:
insert.php
<?php
require "vendor/autoload.php";

// Creating Connection
$conn = new MongoDB\Client("mongodb://localhost:27017");

// Creating Database
$db = $conn -> studentdb;
//Creating Collection
$collection = $db -> student_info;
// Insering Record
$collection->insertOne( [ 'name' =>'Janvi', 'roll_number' => 658] );
// Fetching Record
$record = $collection->find( [ 'name' =>'Janvi'] );
foreach ($record as $Student) {
echo $Student['name'], ': ', $Student['roll_number']."<br>";
MongoDB - Php
Query document:
find.php
<?php
require "vendor/autoload.php";
$conn = new
MongoDB\Client("mongodb://localhost:27017");
$db = $conn -> studentdb;
$collection = $db -> student_info;

$document = $collection -> findOne(


[ 'name' =>'Janvi']
);
var_dump($document);

?>

You might also like