//Create a user database and a user document and perform crud Shell commands using mongodb
1. Open MongoDB Shell
mongosh
2. Create or Switch to a Database
use userDB
3. Create a Collection (Optional)
MongoDB creates it automatically when inserting the first document, but you can explicitly create one:
db.createCollection("users")
4. Insert a Document (Create)
db.users.insertOne({
username: "john_doe",
email: "john@example.com",
age: 28,
address: {
city: "New York",
zip: "10001"
}
})
5. Read Documents (Read)
Find all users:
db.users.find()
Find a specific user:
db.users.findOne({ username: "john_doe" })
6. Update a Document (Update)
Update a field:
db.users.updateOne(
{ username: "john_doe" },
{ $set: { age: 29 } }
)
Add a new field:
db.users.updateOne(
{ username: "john_doe" },
{ $set: { phone: "123-456-7890" } }
)
7. Delete a Document (Delete)
Delete one user:
db.users.deleteOne({ username: "john_doe" })
Delete all users (use with caution):
db.users.deleteMany({})
//Create a real time database in firebase for the student management system and explore the features of Firebase Real Time Database. Perform CRUD operations on the Real Time Database.
npm install firebase
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, set, get, update, remove } from 'firebase/database';
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
databaseURL: "https://YOUR_PROJECT_ID-default-rtdb.firebaseio.com",
projectId: "YOUR_PROJECT_ID",
// ...rest config
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
// CREATE
set(ref(db, 'students/1'), {
name: "John Doe",
course: "Computer Science",
age: 21
});
// READ
get(ref(db, 'students/1')).then(snapshot => {
if (snapshot.exists()) {
console.log(snapshot.val());
} else {
console.log("No data available");
}
});
// UPDATE
update(ref(db, 'students/1'), {
age: 22
});
// DELETE
remove(ref(db, 'students/1'));
Comments