Insert & Query Operations in MongoDB

1. Insert Operations

To insert data into MongoDB collection, you need to use MongoDB’s insert() or save() method.
Syntax:

> db.<collection>.insert(<document>)

where,
collection: the name of the collection in which the data is to be inserted
Document: the JSON object document to be inserted into the database.

1.1 Insert Modes in Insert operation

1.1.1 Insert key-values

The following code shows how to insert values in Key-value form in collection in MongoDB:

db.simplecollection.insert(
  {
     "name" : "parth",
     "age" : 22
  }
);

1.1.2 Insert arrays

The following code shows how to insert arrays in collection in MongoDB:

db.arraycollection.insert(
  {
      "name": "parth",
      "interests": ["cricket", "dancing", "business"]
  }
);

1.1.3 Insert embedded documents

The following code shows how to insert embedded documents in MongoDB:

db.userdata.insert(
  {
      "name" : "Parth Joshi",
      "age" : 20,
      "login_info" : 
      {
          "login_id" : "joshiparthin",
          "password" : "secret"
      }
  }
);

1.1.4 Insert array of embedded documents

The following code shows how to insert array of embedded documents in MongoDB:

db.storestock.insert(
  {
      "product_id" : "T-Shirt",
      "options" : [
      {
           "size" : "Large",
           "stock" : 10
      },
      {
           "size" : "Small",
           "stock" : 12 
      },
      {
           "size" : "Medium", 
           "stock" : 15 
      }
    ]
  }
)

2. Query Operations

Here, we will learn how to query document from MongoDB collection.

2.1 Find() Method

To query data from MongoDB collection, you need to use MongoDB’s find()method.
Syntax:

>db.COLLECTION_NAME.find()

The query criteria in find() method is as follows:

  • Conditional
    • equals
    • less than
    • greater than
  • IN clause
  • AND, OR Clause

2.1.1 Conditional Query

Here, we will learn how to apply conditional query in MongoDB collection.
Syntax:

> db.<collection>.find( { <field>: <value> } )

where,
collection: The collection on which the query is to be performed
field: The field in the document for which the condition is to be checked
value: The value or the document which needs to be compared

2.1.2 Comparison Operator

Here, we will learn how to use comparison operator in MongoDB collection.
Syntax:

db.<collection>.find({<field>: { <operator>: <value> } } )

where,
collection: The collection on which the query is to be performed
field: The field in the document for which the condition is to be checked
value: The value or the document which needs to be compared.
operator: Comparison operator

Types of Comparison Operators:

Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$in Matches any of the values specified in an array.
$nin Matches none of the values specified in an array.

2.1.3 IN Clause

The following code snipet shows how to use IN clause in MongoDB collection:
Syntax:

> db.<collection>.find({ <field>: { $in: [ <value1>, <value2>,… ] } })

where,
collection: The collection on which the query is to be performed
Field: The field in the document for which the condition is to be checked 
Value(n): The value(s) or the document which needs to be compared for corresponding field

2.1.4 AND Clause

The following code snipet shows how to use AND clause in MongoDB collection:
Syntax:

> db.<collection>.find( { <field1>: <value1> , <field2>: <value2>}, …)

where,
Comma acts as AND Clause
collection: The collection on which the query is to be performed
Field(n): The field(s) in the document for which the condition is to be checked
Value(n): The value(s) or the document which needs to be compared for corresponding field.

2.1.5 OR Clause

The following code snipet shows how to use OR clause in MongoDB collection:
Syntax:

> db.<collection>.find(
   {
        $or: [ { <field1>: <value1> }, { <field2>: <value2>},… ]
   }
)

where,
collection: The collection on which the query is to be performed
Field(n): The field(s) in the document for which the condition is to be checked
Value(n): The value(s) or the document which needs to be compared for corresponding field

2.2 Examples for find() Method

Consider the following collection:

{ _id: 5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ]}
{ _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ]}
{ _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] }

2.2.1 Find documents with exact match: [ 5, 8, 9 ]

Query:

db.inventory.find( { ratings: [ 5, 8, 9 ] } )

Result:

{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }

2.2.2 Find documents with one of ratings element as 5:

Query:

db.inventory.find( { ratings: 5 } )

Result:

{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
{ "_id" : 6, "type" : "food", "item" : "bbb", "ratings" : [ 5, 9 ] }
{ "_id" : 7, "type" : "food", "item" : "ccc", "ratings" : [ 9, 5, 8 ] }

2.2.3 Find documents with first element of array as 5:

Query:

db.inventory.find({ 'ratings.0': 5 }

Result:

{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
{ "_id" : 6, "type" : "food", "item" : "bbb", "ratings" : [ 5, 9 ] }

2.2.4 Single Element satisfied conditional criteria

Query:

db.inventory.find( { ratings: { $elemMatch: { $gt: 5, $lt: 9 } } } )

Result:

{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
{ "_id" : 7, "type" : "food", "item" : "ccc", "ratings" : [ 9, 5, 8 ] }

2.2.5 Combination satisfies conditional criteria

Query:

db.inventory.find( { ratings: { $gt: 5, $lt: 9 } } )

Result:

{ "_id" : 5, "type" : "food", "item" : "aaa", "ratings" : [ 5, 8, 9 ] }
{ "_id" : 6, "type" : "food", "item" : "bbb", "ratings" : [ 5, 9 ] }
{ "_id" : 7, "type" : "food", "item" : "ccc", "ratings" : [ 9, 5, 8 ] }