0% found this document useful (0 votes)
6 views16 pages

Mongo DB and Javascript Programs

The document provides a comprehensive guide on connecting Java with MongoDB, performing CRUD operations, and executing aggregation queries on a zip code dataset. It also covers ES6 features like arrow functions, promises, and async/await, culminating in the development of a weather application that displays temperature data in a graph. The instructions include software installation, project setup, and code implementation for both MongoDB and the weather app.

Uploaded by

Sekhar Muthangi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Mongo DB and Javascript Programs

The document provides a comprehensive guide on connecting Java with MongoDB, performing CRUD operations, and executing aggregation queries on a zip code dataset. It also covers ES6 features like arrow functions, promises, and async/await, culminating in the development of a weather application that displays temperature data in a graph. The instructions include software installation, project setup, and code implementation for both MongoDB and the weather app.

Uploaded by

Sekhar Muthangi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

7.

Establish a connection with a database or access any tabular data source using Java Driver to
do the following operations.
a) Send various MongoDB statements.
b) Retrieve and process the results received from the database

Below is a complete step-by-step guide to connect Java with MongoDB, send MongoDB statements,
and retrieve/process results using the MongoDB Java Driver.

We will use:

 Database: MongoDB

 Language: Java

 Tool (optional): MongoDB Compass

✅ PART 1: Install Required Software

🔹 Step 1: Install MongoDB

Download and install MongoDB Community Server.

After installation:

▶ Start MongoDB Server

Open Command Prompt and run:

mongod

If running successfully → server starts on:

mongodb://localhost:27017

🔹 Step 2: Verify MongoDB is Working

Open new Command Prompt:

mongosh

If you see MongoDB shell → installation successful.

✅ PART 2: Create Java Project

You can use:

 Eclipse

 IntelliJ

 VS Code
🔹 Step 3: Add MongoDB Java Driver

If using Maven, add this in [Link]:

<dependency>

<groupId>[Link]</groupId>

<artifactId>mongodb-driver-sync</artifactId>

<version>4.11.1</version>

</dependency>

If NOT using Maven:

1. Download driver JAR from MongoDB website

2. Add it to project → Build Path → Add External JAR

✅ PART 3: Java Program (All Operations Included)

Create file:

[Link]

💻 Complete Working Code

import [Link].*;

import [Link];

import static [Link].*;

import static [Link].*;

public class MongoDBExample {

public static void main(String[] args) {

// 1️⃣ Establish Connection

MongoClient mongoClient = [Link]("mongodb://localhost:27017");

// 2️⃣ Access Database

MongoDatabase database = [Link]("StudentDB");


// 3️⃣ Access Collection

MongoCollection<Document> collection = [Link]("students");

// 4️⃣ Insert Document (MongoDB Statement)

Document student = new Document("name", "Sekhar")

.append("age", 22)

.append("course", "MCA");

[Link](student);

[Link]("Document inserted successfully");

// 5️⃣ Retrieve Documents

FindIterable<Document> docs = [Link]();

[Link]("\n--- Student Records ---");

for (Document doc : docs) {

[Link]("Name: " + [Link]("name"));

[Link]("Age: " + [Link]("age"));

[Link]("Course: " + [Link]("course"));

[Link]("-----------------------");

// 6️⃣ Update Document

[Link](eq("name", "Sekhar"),

set("age", 23));

[Link]("Document updated");

// 7️⃣ Delete Document


[Link](eq("name", "Sekhar"));

[Link]("Document deleted");

[Link]();

✅ PART 4: Operations Performed

Operation MongoDB Statement

Insert insertOne()

Retrieve find()

Update updateOne()

Delete deleteOne()

✅ PART 5: How to Execute (Step-by-Step)

🔹 Step 1: Start MongoDB Server

mongod

Keep it running.

🔹 Step 2: Compile Java File

Open Command Prompt inside project folder:

javac [Link]

🔹 Step 3: Run Program

java MongoDBExample

🔹 Step 4: Check Database

Open Mongo shell:

mongosh
Then:

use StudentDB

[Link]()

You will see inserted data.

✅ What Happens Internally?

1. Java connects to MongoDB

2. Database accessed

3. Collection accessed

4. CRUD operations executed

5. Results retrieved & processed

6. Connection closed

8. Download a zip code dataset at [Link] .Use mongo import to


import the zip code dataset into Mongo DB. After importing the data,
answer the following questions by using aggregation pipelines:
(1) Find all the states that have a city called “BOSTON”.
(2) Find all the states and cities whose names include the string “BOST”.
(3) Each city has several zip codes. Find the city in each state with the most number of zip
codes and rank those cities along with the states using the city populations.
Mongo DB can query on spatial information

Below is a complete step-by-step lab procedure to:

 Download ZIP dataset

 Import using mongoimport

 Execute Aggregation Pipeline queries

 Perform spatial queries

We will use:

 Database: MongoDB

 Tool: mongosh

✅ PART 1: Download Dataset

Dataset URL:
[Link]

Step 1:

Download the file → Save as:

[Link]

Place it inside a folder like:

C:\mongodb-data\

✅ PART 2: Start MongoDB Server

Open Command Prompt:

mongod

Keep it running.

Open another Command Prompt:

mongosh

If shell opens → MongoDB working.

✅ PART 3: Import Dataset Using mongoimport

Navigate to folder containing [Link].

Example:

cd C:\mongodb-data

Now run:

mongoimport --db zipdb --collection zips --file [Link]

If successful, you will see:

imported 29353 documents

✅ PART 4: Open Database

mongosh

Then:

use zipdb

show collections

You should see:

zips
Check sample data:

[Link]()

Document structure looks like:

"_id": "01001",

"city": "AGAWAM",

"loc": [-72.622739, 42.070206],

"pop": 15338,

"state": "MA"

✅ QUESTION 1

🔹 (1) Find all the states that have a city called “BOSTON”

Aggregation Query:

[Link]([

{ $match: { city: "BOSTON" } },

{ $group: { _id: "$state" } }

])

Explanation:

 $match → Filter city = BOSTON

 $group → Group by state

✅ QUESTION 2

🔹 (2) Find states and cities containing string “BOST”

Aggregation Query:

[Link]([

$match: {

city: { $regex: "BOST", $options: "i" }

},
{

$group: {

_id: { state: "$state", city: "$city" }

])

Explanation:

 $regex → Pattern matching

 $options: "i" → Case insensitive

 Grouping removes duplicates

✅ QUESTION 3

🔹 (3) City in each state with most ZIP codes & rank by population

Step 1: Group by State & City

[Link]([

$group: {

_id: { state: "$state", city: "$city" },

zipCount: { $sum: 1 },

totalPop: { $sum: "$pop" }

},

$sort: { "_id.state": 1, zipCount: -1 }

},

$group: {

_id: "$_id.state",

city: { $first: "$_id.city" },

zipCount: { $first: "$zipCount" },

population: { $first: "$totalPop" }


}

},

$sort: { population: -1 }

])

Explanation:

Stage Purpose

$group Count zip codes per city

$sort Sort by state & zipCount

$group Pick city with highest zip

$sort Rank by population

✅ PART 5: Spatial Query Example

MongoDB supports spatial queries using loc field.

Create spatial index:

[Link]({ loc: "2d" })

Find zip codes near coordinates

Example:

[Link]({

loc: {

$near: [-71.00, 42.00]

})

This returns ZIP codes near those coordinates.

✅ FULL EXECUTION SUMMARY

1️⃣ Download [Link]


2️⃣ Start MongoDB → mongod
3️⃣ Import dataset → mongoimport
4️⃣ Open shell → mongosh
5️⃣ Run aggregation queries
6️⃣ Create spatial index
7️⃣ Run spatial query

9. Explore the features of ES6 like arrow functions, callbacks, promises, async/await. Implement
an application for reading the weather information from [Link] and display the
information in the form of a graph on the web page

🌟 PART 1: ES6 FEATURES EXPLANATION

ES6 (ECMAScript 2015) introduced modern JavaScript features.

1️⃣ Arrow Functions

Shorter syntax for writing functions.

const add = (a, b) => a + b;

✔ No need for function keyword


✔ Cleaner and shorter

2️⃣ Callbacks

A function passed as an argument to another function.

function greet(name, callback) {

[Link]("Hello " + name);

callback();

greet("Sekhar", () => {

[Link]("Callback executed");

});

Used in asynchronous operations.

3️⃣ Promises

Used to handle asynchronous operations.

let promise = new Promise((resolve, reject) => {

resolve("Data received");
});

States:

 Pending

 Resolved

 Rejected

4️⃣ Async / Await

Cleaner way to handle promises.

async function fetchData() {

let response = await fetch(url);

✔ Makes async code look synchronous


✔ Improves readability

🌦 PART 2: WEATHER GRAPH APPLICATION

We will:

 Read weather data from OpenWeatherMap

 Display temperature in graph format

📌 STEP 1: Get API Key

1. Go to 👉 [Link]

2. Create free account

3. Generate API Key

4. Copy the API key

📁 STEP 2: Create Project Folder

Create a folder named:

weather-app

Inside it create 3 files:

[Link]

[Link]
[Link]

🧾 STEP 3: [Link]

<!DOCTYPE html>

<html>

<head>

<title>Weather App ES6</title>

<script src="[Link]

<link rel="stylesheet" href="[Link]">

</head>

<body>

<h2>Weather Forecast Graph</h2>

<input type="text" id="city" placeholder="Enter City Name">

<button id="getWeather">Get Weather</button>

<canvas id="weatherChart"></canvas>

<script src="[Link]"></script>

</body>

</html>

🎨 STEP 4: [Link]

body {

text-align: center;

font-family: Arial;

background-color: #f2f2f2;

input, button {
padding: 8px;

margin: 10px;

canvas {

max-width: 800px;

margin: auto;

🚀 STEP 5: [Link]

//Replace apikey with your real API key.

const apiKey = "97404fcf33a3577817d528a720b2e63e";

const button = [Link]("getWeather");

const cityInput = [Link]("city");

const buildURL = (city) =>

`[Link]

const fetchWeatherAsync = async (city) => {

try {

const response = await fetch(buildURL(city));

if (![Link]) {

throw new Error("City not found or API error");

const data = await [Link]();

return data;

} catch (error) {
alert([Link]);

[Link](error);

};

let chart;

const displayGraph = (data) => {

if (!data || ![Link]) {

alert("Invalid data received");

return;

const temps = [Link](0, 8).map(item => [Link]);

const times = [Link](0, 8).map(item => item.dt_txt);

const ctx = [Link]("weatherChart").getContext("2d");

if (chart) [Link]();

chart = new Chart(ctx, {

type: "line",

data: {

labels: times,

datasets: [{

label: "Temperature (°C)",

data: temps,

borderWidth: 2,

tension: 0.3

}]
}

});

};

[Link]("click", async () => {

const city = [Link]();

if (!city) {

alert("Enter city name");

return;

const data = await fetchWeatherAsync(city);

displayGraph(data);

});

▶️STEP 6: How to Run (Very Important)

✅ Method 1: Simple Method

1. Open the weather-app folder

2. Double click [Link]

3. Browser will open

4. Enter city name (Example: Hyderabad)

5. Click Get Weather

6. Graph will display

✅ Method 2 (Recommended – Using VS Code)

1. Install VS Code

2. Install extension: Live Server

3. Open project folder in VS Code

4. Right click [Link]


5. Click Open with Live Server

6. App runs in browser

🔍 What Happens Internally?

1. User enters city

2. API call made using Fetch

3. Data returned in JSON format

4. Extract temperature values

5. [Link] draws line graph

Common questions

Powered by AI

Async/await in JavaScript significantly improves handling of API calls by making asynchronous code behave more like synchronous code, leading to enhanced readability and maintainability. This is achieved by using async functions to define processes that pause execution until awaited Promises are resolved, thereby reducing the complexity of nested callbacks. The impact on code efficiency is noted in cleaner control flow and reduced execution overhead, as tasks that rely on data completion are naturally sequenced, minimizing execution delays and potential errors. In applications like fetching weather data, this approach ensures clear, linear data fetching and processing .

To download and import a dataset in MongoDB, the process involves: 1) Downloading the dataset (e.g., zips.json from the provided URL), 2) Running the MongoDB server using mongod, and 3) Importing the dataset into MongoDB with mongoimport, specifying the database and collection names. Once imported, aggregation queries can be conducted to analyze the dataset. This facilitates complex data analysis by allowing users to leverage MongoDB's aggregation framework to perform operations like filtering, grouping, and sorting data for insights, as seen in queries identifying cities or sorting by population .

Aggregation pipelines in MongoDB are frameworks for data aggregation, modeled as a series of stages that transform the documents as they pass through the pipeline. They facilitate complex queries by allowing operations like filtering, sorting, grouping, and projecting. For instance, to find states with a city named 'BOSTON', the pipeline first filters documents with city 'BOSTON', then groups results by state through the stages $match and $group .

Integrating MongoDB with Java enables CRUD (Create, Read, Update, Delete) operations by using the MongoDB Java Driver to interact with MongoDB databases. The steps involved include: 1) Establishing a connection using MongoClient, 2) Accessing the specific database and collection, e.g., 'StudentDB' and 'students', 3) Performing operations like insert (insertOne()), retrieve (find()), update (updateOne()), and delete (deleteOne()), and 4) Processing and displaying the results. Finally, the connection is closed after the operations are completed .

MongoDB's aggregation framework facilitates complex data analytics by allowing multi-stage data transformation and computation operations. For analyzing the most populous city with the most ZIP codes in each state, the framework utilizes $group to aggregate data by city and state, counting ZIP codes and summing populations. Subsequent $sort stages order by zip count and population, and a final $group stage extracts the top city per state by these metrics. This facilitates identification and ranking based on complex criteria, leveraging MongoDB's ability to perform detailed calculations and reaggregation within a single query pipeline .

MongoDB and Java can be effectively used together to manage and manipulate educational data, such as student records, by performing essential CRUD operations. The key operations include: inserting new student records with insertOne(), reading student data with find(), updating existing records, such as changing a student's age using updateOne(), and deleting records with deleteOne(). All operations are executed via MongoDB statements within a Java program, leveraging the MongoDB Java Driver to access and modify the database collections .

ES6 introduces features that enhance asynchronous programming, such as Promises and the async/await syntax. Promises simplify handling asynchronous operations by representing actions that are not yet completed, while async/await provides a more readable syntax, making asynchronous code resemble synchronous code. In a weather application, these features are used for making API calls and fetching data asynchronously. The async function fetches weather data with await ensuring the code waits for data before executing subsequent lines, enhancing code readability and maintainability .

Creating a connection between a Java application and MongoDB involves initializing MongoClient with the correct URI, accessing the desired database, and performing CRUD operations. Challenges can include ensuring the MongoDB server is running, managing dependency issues with the MongoDB Java Driver, and handling exceptions during CRUD operations. To address these, developers should verify server setup and connectivity, use proper dependency management tools like Maven to handle driver integration, and implement error-handling mechanisms to manage and debug operational exceptions. Ensuring proper setup of the development environment, such as JDK installation and IDE configuration, is also crucial .

The structure of the ES6 weather application promotes user interaction and data visualization by providing a user-friendly interface through an HTML form where users input city names. JavaScript handles API calls asynchronously to fetch weather data, which is then processed and visualized using Chart.js. The use of Chart.js allows for dynamic rendering of temperature data in a line graph format, utilizing chart objects for customizable visual representation, with data points mapped to times and temperatures from the API response .

Spatial queries in MongoDB utilize the loc field to manage geographical data, implementing geographical indexing with commands like createIndex. This indexing allows for the execution of spatial queries, such as finding zip codes near specific coordinates, by using the $near operator within a query. This process involves creating a spatial index on the loc field and running a query, which returns documents ordered by distance to specified coordinates .

You might also like