Ticker

6/recent/ticker-posts

MongoDB Collections

MongoDB Collections

Introduction:
In MongoDB, a collection is a group of documents that are stored together within a database. It is analogous to a table in a relational database but with a more flexible and schema-less structure. Collections are schema-free, meaning each document in a collection can have different fields and data types. In this documentation, we will cover the basics of MongoDB collections, how to create and manage them, and provide coding examples for better understanding.

Creating a Collection:
To create a collection in MongoDB, you don't need to explicitly define it. MongoDB will automatically create a collection if it does not exist when you insert the first document.

Inserting Documents:
To insert a document into a collection, you can use the insertOne() or insertMany() methods provided by the MongoDB driver.

Example - Insert a single document into the "users" collection:

javascript
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);

async function insertDocument() {
try {
await client.connect();
const db = client.db('mydatabase');
const usersCollection = db.collection('users');

const newUser = {
name: 'John Doe',
age: 30,
email: 'john@example.com'
};

const result = await usersCollection.insertOne(newUser);
console.log('Inserted document ID:', result.insertedId);
} catch (err) {
console.error('Error:', err);
} finally {
await client.close();
}
}

insertDocument();

Querying Documents:
To query documents from a collection, you can use the find() method. It allows you to specify a query filter to retrieve specific documents that match certain criteria.

Example - Query documents from the "users" collection:

javascript
// Assuming you have already connected to the database as shown in the previous example

async function findDocuments() {
try {
const usersCollection = client.db('mydatabase').collection('users');

const query = { age: { $gt: 25 } }; // Find users older than 25
const result = await usersCollection.find(query).toArray();

console.log('Matching documents:', result);
} catch (err) {
console.error('Error:', err);
} finally {
await client.close();
}
}

findDocuments();

Updating Documents:
To update documents in a collection, you can use the updateOne() or updateMany() methods. These methods allow you to modify the existing documents that match the specified criteria.

Example - Update a document in the "users" collection:

javascript
// Assuming you have already connected to the database as shown in the previous example

async function updateDocument() {
try {
const usersCollection = client.db('mydatabase').collection('users');

const filter = { name: 'John Doe' };
const update = { $set: { age: 35 } }; // Update John Doe's age to 35

const result = await usersCollection.updateOne(filter, update);
console.log('Modified documents:', result.modifiedCount);
} catch (err) {
console.error('Error:', err);
} finally {
await client.close();
}
}

updateDocument();

Deleting Documents:
To delete documents from a collection, you can use the deleteOne() or deleteMany() methods.

Example - Delete a document from the "users" collection:

javascript
// Assuming you have already connected to the database as shown in the previous example

async function deleteDocument() {
try {
const usersCollection = client.db('mydatabase').collection('users');

const filter = { email: 'john@example.com' };
const result = await usersCollection.deleteOne(filter);
console.log('Deleted documents:', result.deletedCount);
} catch (err) {
console.error('Error:', err);
} finally {
await client.close();
}
}

deleteDocument();

Conclusion:
In this documentation, we covered the basics of MongoDB collections, including creating collections, inserting, querying, updating, and deleting documents within them. MongoDB's flexibility makes it a popular choice for various applications, allowing developers to work with dynamic and evolving data structures.

    Post a Comment

    0 Comments