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

Insert Document in MongoDB Collection

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

Insert Document in MongoDB Collection

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

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: [Link]("myCollection")
 Implicitly create a collection:
 Eg: [Link]({ 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:
[Link]("newCollectionName
")
 Example Workflow
 // Step 1: Create a new database and collection
o use myDatabase
o [Link]("myCollection")
o [Link]({ name: "Alice", age: 25 })

 // Step 2: Drop the collection


 [Link]()
 // Step 3: Rename the collection
 [Link]("oldCollection")
 [Link]({ name: "Bob", age: 30 })
 [Link]("newCollection")

 // Step 4: Drop the database


 use myDatabase
 [Link]()
 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
 [Link]({
name: "John Doe",
age: 30,
email: "[Link]@[Link]"
});
 Insert Multiple Documents:
 // Insert multiple documents into the collection
[Link]([
{ name: "Jane Smith", age: 25, email:
"[Link]@[Link]" },
{ name: "Alice Johnson", age: 28, email:
"[Link]@[Link]" }
]);
 2. Update Document
o You can update existing documents using the updateOne(),
updateMany(), or replaceOne() methods.
 Update a Single Document:
 // Update a single document
[Link](
{ name: "John Doe" }, // Filter criteria
{ $set: { age: 31 } } // Update operation
);
 Update Multiple Documents:
 // Update multiple documents
[Link](
{ age: { $lt: 30 } }, // Filter criteria
{ $set: { status: "young" } } // Update operation
);
 Replace a Document:
 // Replace a document completely
[Link](
{ name: "Jane Smith" }, // Filter criteria
{ name: "Jane Smith", age: 26, email:
"[Link]@[Link]" } // 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
[Link]({ name: "John Doe" });
 Delete Multiple Documents:
 // Delete multiple documents
[Link]({ 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
[Link]([
{ name: "John Doe", age: 30, email: "[Link]@[Link]"
},
{ name: "Jane Smith", age: 25,
email:"[Link]@[Link]" }
]);
 // Update a document
[Link](
{ name: "John Doe" },
{ $set: { age: 31 } }
);
 // Delete a document
[Link]({ 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
[Link](
{ name: "John Doe" }, // Filter criteria
{ name: "John Doe", age: 31, email:
"[Link]@[Link]", 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 = [Link]({ name:
"John Doe" });
 Find Multiple Documents:
 // Find all documents that match the criteria
const documents = [Link]({ 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 = [Link](
{ 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
[Link]({ 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"
[Link]({ age: 1, email: -1 });

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

 // List all indexes on the collection


[Link]();
 Dropping an Index:
o You can drop an index using the dropIndex() method.
 // Drop an index by name
[Link]("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
 [Link](operations)
 .then(result => {
 [Link]("Bulk write operation successful:", result);
 })
 .catch(err => {
 [Link]("Bulk write operation failed:", err);
 });

You might also like