0% found this document useful (0 votes)
33 views23 pages

Lo2 Nosql2

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)
33 views23 pages

Lo2 Nosql2

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/ 23

SWDND501-NoSQL DATABASE DEVELOPMENT

L.o 2: Implement Database Design


 Perform MongoDB Data Definition
 1. Create
 a. Create a Database
o To create a database in MongoDB, you use the use
command. The database is created when you first store
data in it.
 Eg: use myDatabase_name
 b. Create Collections
 You can create a collection explicitly using the
createCollection method or implicitly by inserting a
document into a non-existing collection.
 Explicitly create a collection:
o Eg: db.createCollection("myCollection")
 Implicitly create a collection:
 Eg: db.myCollection.insertOne({ name: "John Doe", age:
30 })
 2. Drop
 a. Drop a Database
o To drop a database, you can use the dropDatabase method.
This will remove the entire database and all of its
collections.
 Eg: db.dropDatabase_name()
 b. Drop Collections
o To drop a specific collection, you can use the drop method on
that collection.
 Eg: db.myCollection_name.drop()
 3. Rename
o a. Rename a Database
 MongoDB does not provide a direct command to rename a
database. Instead, you can create a new database and copy
the collections from the old database to the new one, then
drop the old database.

 b. Rename Collections
 To rename a collection, you can use the renameCollection
method.
 Eg:
db.myCollection.renameCollection("newCollectionName
")
 Example Workflow
 // Step 1: Create a new database and collection
o use myDatabase
o db.createCollection("myCollection")
o db.myCollection.insertOne({ name: "Alice", age: 25 })

 // Step 2: Drop the collection


 db.myCollection.drop()
 // Step 3: Rename the collection
 db.createCollection("oldCollection")
 db.oldCollection.insertOne({ name: "Bob", age: 30 })
 db.oldCollection.renameCollection("newCollection")

 // Step 4: Drop the database


 use myDatabase
 db.dropDatabase()
 MongoDB data Manipulating
 1. Insert Document
o You can insert documents into a collection using the
insertOne() or insertMany() methods.
 Insert a Single Document:
 // Insert a single document into the collection
 db.myCollection.insertOne({
name: "John Doe",
age: 30,
email: "[email protected]"
});
 Insert Multiple Documents:
 // Insert multiple documents into the collection
db.myCollection.insertMany([
{ name: "Jane Smith", age: 25, email:
"[email protected]" },
{ name: "Alice Johnson", age: 28, email:
"[email protected]" }
]);
 2. Update Document
o You can update existing documents using the updateOne(),
updateMany(), or replaceOne() methods.
 Update a Single Document:
 // Update a single document
db.myCollection.updateOne(
{ name: "John Doe" }, // Filter criteria
{ $set: { age: 31 } } // Update operation
);
 Update Multiple Documents:
 // Update multiple documents
db.myCollection.updateMany(
{ age: { $lt: 30 } }, // Filter criteria
{ $set: { status: "young" } } // Update operation
);
 Replace a Document:
 // Replace a document completely
db.myCollection.replaceOne(
{ name: "Jane Smith" }, // Filter criteria
{ name: "Jane Smith", age: 26, email:
"[email protected]" } // New document
);
 3. Delete Document
o You can delete documents from a collection using the
deleteOne() or deleteMany() methods.
 Delete a Single Document:
 // Delete a single document
db.myCollection.deleteOne({ name: "John Doe" });
 Delete Multiple Documents:
 // Delete multiple documents
db.myCollection.deleteMany({ age: { $gt: 30 } }); // Deletes all
documents with age greater than 30
 SUMMARY
 Insert: Use insertOne() to insert a single document and
insertMany() to insert multiple documents.
 Update: Use updateOne() to update a single document,
updateMany() to update multiple documents, and
replaceOne() to replace a document completely.
 Delete: Use deleteOne() to delete a single document and
deleteMany() to delete multiple documents.
 Example Workflow
 // Insert documents
db.myCollection.insertMany([
{ name: "John Doe", age: 30, email: "[email protected]"
},
{ name: "Jane Smith", age: 25,
email:"[email protected]" }
]);
 // Update a document
db.myCollection.updateOne(
{ name: "John Doe" },
{ $set: { age: 31 } }
);
 // Delete a document
db.myCollection.deleteOne({ name: "Jane Smith" });
 1. Replacing Documents
o In MongoDB, you can replace an existing document with a
new document using the replaceOne() method.
o This method replaces the entire document that matches the
specified filter criteria.
o Example of Replacing a Document:
 // Replace a document completely
db.myCollection.replaceOne(
{ name: "John Doe" }, // Filter criteria
{ name: "John Doe", age: 31, email:
"[email protected]", status: "active" } // New
document
);
 In this example, the document with the name "John Doe" is
replaced with a new document. Note that the new document
must have the same structure as the original, but it can also
include additional fields.
 2. Querying Documents
o MongoDB provides powerful querying capabilities to
retrieve documents from a collection. You can use various
query operators to filter and sort results.
 Basic Query:
 // Find a single document
const singleDocument = db.myCollection.findOne({ name:
"John Doe" });
 Find Multiple Documents:
 // Find all documents that match the criteria
const documents = db.myCollection.find({ age: { $gte: 30 } });
 Using Projection:
o You can specify which fields to include or exclude in the
results using projection.
 // Find documents and include only specific fields
const projectedDocuments = db.myCollection.find(
{ age: { $gte: 30 } },
{ name: 1, email: 1 } // Include only name and email fields
);
3. Indexes

 Indexes are special data structures that improve the speed


of data retrieval operations on a collection. By default,
MongoDB creates an index on the _id field of each
document.
 Creating an Index:
 You can create an index on one or more fields using the
createIndex() method.
 // Create an index on the "name" field
db.myCollection.createIndex({ name: 1 }); // 1 for
ascending order, -1 for descending order
 Creating a Compound Index:
 You can create an index on multiple fields.
 // Create a compound index on "age" and "email"
db.myCollection.createIndex({ age: 1, email: -1 });

 Listing Indexes:
o To view the indexes on a collection, use
the getIndexes() method

 // List all indexes on the collection


db.myCollection.getIndexes();
 Dropping an Index:
o You can drop an index using the dropIndex() method.
 // Drop an index by name
db.myCollection.dropIndex("name_1"); // The name is
usually in the format "fieldName_order"
 Bulk Write Operations
 Bulk write operations in NoSQL databases, particularly in
MongoDB, allow you to perform multiple write operations
(insert, update, replace, and delete) in a single request.
 This can significantly improve performance by reducing
the number of round trips to the server and allowing for
more efficient processing of multiple operations at once.
o Bulk Write Operations in MongoDB
 In MongoDB, you can use the ‘bulkWrite’ method to
execute multiple write operations in bulk.
 The ‘bulkWrite’ method takes an array of operations, each
specified as an object, and processes them in the order they
are provided.
o Example of Bulk Write Operations
 how to can perform bulk write operations in MongoDB
 // Create an array of operations
 const operations = [
 { insertOne: { document: { name: "David", age: 28, city:
"Chicago" } } },
 { updateOne: {
 filter: { name: "Alice" },
 update: { $set: { age: 32 } }
 }},
 { deleteOne: { filter: { name: "Bob" } } },
 { replaceOne: {
 filter: { name: "Charlie" },
 replacement: { name: "Charlie", age: 36, city: "Miami" }
 }},
 ];
 // Execute bulk write operation
 db.collectionName.bulkWrite(operations)
 .then(result => {
 console.log("Bulk write operation successful:", result);
 })
 .catch(err => {
 console.error("Bulk write operation failed:", err);
 });

You might also like