DEV Community

Cover image for insertOne, insertMany and find, findOne in MongoDB
KAWSAR KABIR
KAWSAR KABIR

Posted on

insertOne, insertMany and find, findOne in MongoDB

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",
});
Enter fullscreen mode Exit fullscreen mode

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' }
]);
Enter fullscreen mode Exit fullscreen mode
  • Here, db.students indicates that we are working in the students collection.
  • 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();
Enter fullscreen mode Exit fullscreen mode
  • The find() method is used to find all the data.

To find specific data:

db.students.findOne({ id: 1 });
Enter fullscreen mode Exit fullscreen mode
  • The findOne() method is used to find a specific document.
  • { id: 1 } is the search criterion indicating that we are looking for the document with id: 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' });
Enter fullscreen mode Exit fullscreen mode
  • { gender: 'Female' } is the search criterion indicating that we are looking for documents where the gender field is Female.

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 });
Enter fullscreen mode Exit fullscreen mode
  • { gender: 'Female' } is the search criterion indicating that we are looking for documents where the gender field is Female.
  • { name: 1, email: 1 } means we want to get the name and email fields of the female students.

This is how we can insert and find data in MongoDB!

Top comments (0)