Monday, September 30, 2019

MongoDB - Query an Array of Embedded Documents

Click the link: "MongoDB - Query an Array of Embedded Documents"

In this MongoDB tutorial we will learn to query an array of embedded documents.
Login to your MongoDB server and insert the following documents.
For this tutorial I will insert the documents in the books collection.
> db.books.insertMany([
  {
    "title": "The C Programming Language",
    "author": ["Brian Kernighan", "Dennis Ritchie"],
    "inventory": [
      { "warehouse": "W1", "qty": 3000 },
      { "warehouse": "W2", "qty": 750 }
    ]
  },
  {
    "title": "MongoDB in Action",
    "author": ["Kyle Banker"],
    "inventory": [
      { "warehouse": "W2", "qty": 100 },
      { "warehouse": "W3", "qty": 1500 }
    ]
  },
  {
    "title": "Node.js in Action",
    "author": ["Marc Harter", "Nathan Rajlich", "T. J. Holowaychuk", "Mike Cantelon"],
    "inventory": [
      { "warehouse": "W1", "qty": 100 },
      { "warehouse": "W3", "qty": 250 }
    ]
  }

]);

Select based on exact match of embedded document in an array

In the following example we are fetching all the documents having the exact embedded document { "warehouse": "W1", "qty": 100 } in the inventory array.
Note! The field order is important i.e. the first field of the embedded document must be "warehouse" and must have value "W1" and the second field of the embedded document must be "qty" and must have value 100.
> db.books.find({ "inventory": { "warehouse": "W1", "qty": 100 } }).pretty();



{
  "_id" : ObjectId("5d2d9afd81a3cd0a9239c121"),
  "title" : "Node.js in Action",
  "author" : [
    "Marc Harter",
    "Nathan Rajlich",
    "T. J. Holowaychuk",
    "Mike Cantelon"
  ],
  "inventory" : [
    {
      "warehouse" : "W1",
      "qty" : 100
    },
    {
      "warehouse" : "W3",
      "qty" : 250
    }
  ]
}
If we change the field order of the embedded document in the query then we will not get the result.
In the following query we are changing the field order of the embedded document to { "qty": 100, "warehouse": "W1" } and it gives us no result.
> db.books.find({ "inventory": { "qty": 100, "warehouse": "W1" } }).pretty();

Read more...

Sunday, September 29, 2019

MongoDB - Query an Array

Click the link: "MongoDB - Query an Array"

In this MongoDB tutorial we will learn to query arrays.
Login to your MongoDB server and insert the following documents.
For this tutorial I will insert the following documents in the posts collection.
> db.posts.insertMany([
  {
    "title": "This is my first post!",
    "tags": ["awesome", "post", "blog"]
  },
  {
    "title": "Dinner time :)",
    "tags": ["food", "dinner", "fun"]
  },
  {
    "title": "Birthday Treat",
    "tags": ["fun", "food", "birthday", "treat", "party"]
  }
]);

Match exact array

In the following example we are going to fetch documents having exactly 3 elements in the array and values are awesomepost and blog in that order.
> db.posts.find({
  "tags": ["awesome", "post", "blog"]
}).pretty();


{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b5"),
  "title" : "This is my first post!",
  "tags" : [
    "awesome",
    "post",
    "blog"
  ]
}
Note! If we change the positions of the array elements in the above query then we will not get the same result.

Query an array for an element

In the following example we are going to fetch all the documents having an array field tags that contains food as one of the element in the array.
> db.posts.find({ "tags": "food" }).pretty();


{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b6"),
  "title" : "Dinner time :)",
  "tags" : [
    "food",
    "dinner",
    "fun"
  ]
}
{
  "_id" : ObjectId("5d1b43d9085e37060f4c36b7"),
  "title" : "Birthday Treat",
  "tags" : [
    "fun",
    "food",
    "birthday",
    "treat",
    "party"
  ]
}

Read more...

Thursday, September 26, 2019

MongoDB - Query Embedded Document

Click the link: "MongoDB - Query Embedded Document"

In this MongoDB tutorial we will learn to query embedded documents.
In the previous tutorial we learned about how to query documents and about logical operators and how to select specific fields. Feel free to check that out.

Embedded or Nested documents

For this tutorial lets go ahead and create some embedded documents. So, connect to your MongoDB server and run the following command to insert some documents in the shapes collection.
> db.shapes.insertMany([
  {
    "shape": "rectangle",
    "item": "Rect 1",
    "dim": {
      "length": 10,
      "breadth": 20,
      "uom": "cm"
    }
  },
  {
    "shape": "rectangle",
    "item": "Rect 2",
    "dim": {
      "length": 20,
      "breadth": 30,
      "uom": "cm"
    }
  },
  {
    "shape": "rectangle",
    "item": "Rect 3",
    "dim": {
      "length": 5,
      "breadth": 10,
      "uom": "cm"
    }
  },
  {
    "shape": "square",
    "item": "Sq 1",
    "dim": {
      "side": 10.5,
      "uom": "cm"
    }
  },
  {
    "shape": "square",
    "item": "Sq 2",
    "dim": {
      "side": 20,
      "uom": "cm"
    }
  },
  {
    "shape": "square",
    "item": "Sq 3",
    "dim": {
      "side": 15,
      "uom": "inch"
    }
  },
  {
    "shape": "square",
    "item": "Sq 4",
    "dim": {
      "side": 25.5,
      "uom": "inch"
    }
  }
]);
We learned how to create embedded documents in the Insert Document tutorial. Feel free to check that out.
Alright, let's start simple then progress to advance problems.

Find all rectangles

To find all the documents in the shapes collection that represents a rectangle we have to run the following command.
> db.shapes.find({ "shape": "rectangle" }).pretty();


{
  "_id" : ObjectId("5d175dffba3250e57f98faca"),
  "shape" : "rectangle",
  "item" : "Rect 1",
  "dim" : {
    "length" : 10,
    "breadth" : 20,
    "uom" : "cm"
  }
}
{
  "_id" : ObjectId("5d175dffba3250e57f98facb"),
  "shape" : "rectangle",
  "item" : "Rect 2",
  "dim" : {
    "length" : 20,
    "breadth" : 30,
    "uom" : "cm"
  }
}
{
  "_id" : ObjectId("5d175dffba3250e57f98facc"),
  "shape" : "rectangle",
  "item" : "Rect 3",
  "dim" : {
    "length" : 5,
    "breadth" : 10,
    "uom" : "cm"
  }
}

Read more...

Wednesday, September 25, 2019

MongoDB - Query Document

Click the link: "MongoDB - Query Document"

In this MongoDB tutorial we will learn to query documents.

Select all the documents

To select all the documents in a collection we use the find() method.
In the following example we are listing all the documents in the students collection.
> db.students.find();

{ "_id" : ObjectId("5d16c9e9e8cb73839ac9f2f1"), "firstname" : "Yusuf", "lastname" : "Shakeel", "studentid" : "s01" }
{ "_id" : ObjectId("5d16c9efe8cb73839ac9f2f2"), "firstname" : "Jane", "lastname" : "Doe", "studentid" : "s02" }
{ "_id" : ObjectId("5d16c9efe8cb73839ac9f2f3"), "firstname" : "John", "lastname" : "Doe", "studentid" : "s03" }
{ "_id" : ObjectId("5d16ca23e8cb73839ac9f2f4"), "firstname" : "Alice", "lastname" : "Doe", "studentid" : "s04", "score" : 10.5 }
{ "_id" : ObjectId("5d16ca23e8cb73839ac9f2f5"), "firstname" : "Bob", "lastname" : "Doe", "studentid" : "s05", "date_of_birth" : ISODate("2000-01-01T00:00:00Z") }
{ "_id" : ObjectId("5d16cfa4e8cb73839ac9f2f6"), "firstname" : "Eve", "lastname" : "Doe", "studentid" : "s06", "contact_phone" : { "primary" : { "number" : "+919800000000", "name" : "Bill Doe", "relation" : "Father" }, "secondary" : [ { "number" : "+919800000001", "name" : "Mac Doe", "relation" : "Brother" } ] } }

Select all documents and render in easy-to-read format

To render the result in easy to read format we use the pretty() method.
In the following example we are selecting all the documents in the students collection and listing them in an easy-to-read format.
> db.students.find().pretty();

{
  "_id" : ObjectId("5d16c9e9e8cb73839ac9f2f1"),
  "firstname" : "Yusuf",
  "lastname" : "Shakeel",
  "studentid" : "s01"
}
{
  "_id" : ObjectId("5d16c9efe8cb73839ac9f2f2"),
  "firstname" : "Jane",
  "lastname" : "Doe",
  "studentid" : "s02"
}
{
  "_id" : ObjectId("5d16c9efe8cb73839ac9f2f3"),
  "firstname" : "John",
  "lastname" : "Doe",
  "studentid" : "s03"
}
{
  "_id" : ObjectId("5d16ca23e8cb73839ac9f2f4"),
  "firstname" : "Alice",
  "lastname" : "Doe",
  "studentid" : "s04",
  "score" : 10.5
}
{
  "_id" : ObjectId("5d16ca23e8cb73839ac9f2f5"),
  "firstname" : "Bob",
  "lastname" : "Doe",
  "studentid" : "s05",
  "date_of_birth" : ISODate("2000-01-01T00:00:00Z")
}
{
  "_id" : ObjectId("5d16cfa4e8cb73839ac9f2f6"),
  "firstname" : "Eve",
  "lastname" : "Doe",
  "studentid" : "s06",
  "contact_phone" : {
    "primary" : {
      "number" : "+919800000000",
      "name" : "Bill Doe",
      "relation" : "Father"
    },
    "secondary" : [
      {
        "number" : "+919800000001",
        "name" : "Mac Doe",
        "relation" : "Brother"
      }
    ]
  }
}
The find() method is equivalent to the following SQL statement.
SELECT * FROM students;

Read more...

Sunday, September 22, 2019

MongoDB - Insert Document

Click the link: "MongoDB - Insert Document"

In this MongoDB tutorial we will learn to insert documents.

Insert one document

To insert one document into a collection we use the db.collection.insertOne() method.
Note! collection is the name of the collection in which you want to insert the document.
In the following example we are inserting one document into students collection.
> db.students.insertOne({
  "firstname": "Yusuf",
  "lastname": "Shakeel",
  "studentid": "s01"
});
On success we will get a similar response in the terminal.
{
  "acknowledged" : true,
  "insertedId" : ObjectId("5d16c693e8cb73839ac9f2ec")
}
Note! insertedId is a unique id (primary key) given to each document in a collection by MongoDB.
To fetch the inserted documents in a collection we use the find() method.
> db.students.find()
{ "_id" : ObjectId("5d16c693e8cb73839ac9f2ec"), "firstname" : "Yusuf", "lastname" : "Shakeel", "studentid" : "s01" }
We will learn more about find() in the Query Document tutorial.

Read more...

Sunday, September 15, 2019

MongoDB - Database and Collection

Click the link: "MongoDB - Database and Collection"

In this MongoDB tutorial we will learn about databases, collections and documents.

What is a document?

A document is a key value pair. It is a JSON (JavaScript Object Notation).
Following example represents a student document.
{
  "student_id": "s0001",
  "first_name": "Yusuf",
  "last_name": "Shakeel"
}
student_idfirst_name and last_name are referred as the fields or keys of the document and s0001Yusuf and Shakeel are the respective values of the given fields.
If you are familiar with RDBMS (eg. MySQL) then a MongoDB document is like a row in a RDBMS table.

What is a collection?

A collection is a set of documents.
A single collection can have zero or more number of documents.
Think of MongoDB collections as tables in RDBMS.

Saturday, September 14, 2019

MongoDB - Getting Started

Click the link: "MongoDB - Getting Started"

This is the MongoDB getting started tutorial.

What is MongoDB?

MongoDB is a general purpose, document-based, distributed database built for modern application developers and for the cloud era. No database is more productive to use.
- mongodb.com

Prerequisite

If you have some prior knowledge of relational database (RDBMS like MySQL) then that is an advantage for you. Though MongoDB is not a RDBMS but having some database knowledge will help you understand MongoDB quickly.

Read more...