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...

No comments:

Post a Comment