Adding and Querying the data in MongoDB


Adding and Querying the data in MongoDB

Adding Data in MongoDB: MongoDB stores documents in BSON, a binary form of JSON (JavaScript Object Notation). The documents are stored in the collection.

Step 1: Create Collection

It will create a collection if it does not exist. Otherwise, it returns the existing collection.

Step 2: Insert Data into Collection Documents in MongoDB can be inserted using two methods:

  1. db.collection_name.insertOne(): The db.collection_name.insertOne method is used to insert single document in collection.
  2. db.collection_name.insertMany(): The db.collection_name.insertMany() can insert multiple documents into a collection.Only you need to pass array of documents to this method.

Querying the data in MongoDB: The query operation performs using db.collection.find() method in MongoDB.

Step 2: Select All Documents in a Collection – To select all documents in the collection, pass an empty document as the query filter parameter to the find method. This statement is similar to the SELECT * FROM table statement in MySQL.

Step 3: Specify Equality Condition – To filter the result of the db.collection_name.find() method, you need to specify conditions for the method.

Step 4: Specify Conditions Using Query Operators – A query filter document can use the query operators to specify a condition.

‘in’ Operator ($in)

‘AND’ Operator(, ) – A compound query can specify conditions for more than one field in document collecting. Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions.

‘OR’ Operator ($or) – Using the $or operator, you can specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.