In databases, the insertOne and insertMany methods are used to add new data. insertOne is used to insert a single document, while insertMany can be used to insert multiple documents at once. Let’s understand this with examples:
Adding a single document (insertOne):
db.students.insertOne({
id: 1,
name: 'Rahim',
age: 20,
email: 'abc@gmail.com',
gender: "Male",
});
Adding multiple documents at once (insertMany):
db.students.insertMany([
{ id: 2, name: 'Karim', age: 22, email: 'abc@gmail.com', gender: 'Male' },
{ id: 3, name: 'Ayesha', age: 19, email: 'abc@gmail.com', gender: 'Female' },
{ id: 4, name: 'Fatima', age: 21, email: 'abc@gmail.com', gender: 'Female' }
]);
- Here,
db.studentsindicates that we are working in thestudentscollection. - The
{}represents a JSON object being inserted.
Find & FindOne
Find means to search. Suppose we want to view the data that has been added to the database. The find() and findOne() methods help us with this task. The find() method retrieves all the data, while the findOne() method is used to retrieve specific data. Let's look at examples:
To find all data:
db.students.find();
- The
find()method is used to find all the data.
To find specific data:
db.students.findOne({ id: 1 });
- The
findOne()method is used to find a specific document. -
{ id: 1 }is the search criterion indicating that we are looking for the document withid: 1.
Field Filtering
Suppose someone asks for data of only female students. In this case, we can access data for a specific field using Field Filtering:
To find data for a specific field:
db.students.find({ gender: 'Female' });
-
{ gender: 'Female' }is the search criterion indicating that we are looking for documents where thegenderfield isFemale.
Project
The previous task can also be done using the Project() method, but the difference is that you cannot use findOne() with Project(), only find() can be used.
To find data for a specific field using the Project() method:
db.students.find({ gender: 'Female' }).project({ name: 1, email: 1 });
-
{ gender: 'Female' }is the search criterion indicating that we are looking for documents where thegenderfield isFemale. -
{ name: 1, email: 1 }means we want to get thenameandemailfields of the female students.
This is how we can insert and find data in MongoDB!
Top comments (0)