top of page
realcode4you

MongoDB Assignment Help | Practice Set 1



In this we will provide the some MongoDB queries and their solution, you need to practice it itself and comment in below section to send different solution from own side.


Check or download Dataset(Assgcars.json) from here.



Here the queries solution using nodejs:


First need to connect mongodb using below MongoClient


const MongoClient = require("mongodb").MongoClient;

//update the connection string.
const url = "mongodb://localhost/mongo-task";

//update database name
const dbName = "mongo-task";

//update collection name (i.e targetted collection)

const collectionName = "cars";

/*Query results are logged on the terminal.*/

Query 1(e)

//Query 1
numberOfColoursByManufacturer = async () => {
  const client = await MongoClient.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).catch((err) => console.log("Could not connect to MongoDB", err));

  try {
    const db = client.db(dbName);
    const collection = db.collection(collectionName);
    let res = await collection
      .aggregate([
        {
          $unwind: "$Colour",
        },
        {
          $group: {
            _id: "$Manufacturer",
            Colours: { $addToSet: "$Colour" },
          },
        },
        {
          $project: {
            _id: 0,
            Manufacturer: "$_id",
            CountOfColours: { $size: "$Colours" },
          },
        },
      ])
      .toArray();
    console.log(res);
  } catch (err) {
    console.log("Error occured in First Query");
  } finally {
    client.close();
  }
};


Query 2(f)

//Query 2
extrasByManufacturer = async () => {
  const client = await MongoClient.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).catch((err) => console.log("Could not connect to MongoDB", err));

  try {
    const db = client.db(dbName);
    const collection = db.collection(collectionName);
    let res = await collection
      .aggregate([
        {
          $unwind: "$Extras",
        },
        {
          $group: {
            _id: "$Manufacturer",
            Extras: { $addToSet: "$Extras" },
          },
        },
        {
          $project: {
            _id: 0,
            Manufacturer: "$_id",
            Extras: "$Extras",
          },
        },
      ])
      .toArray();
    console.log(res);
  } catch (err) {
    console.log("Error in Sec Query", err);
  } finally {
    client.close();
  }
};

Query 3(g)

//Query 3
countNumberOfExtras = async () => {
  const client = await MongoClient.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).catch((err) => console.log("Could not connect to MongoDB", err));

  try {
    const db = client.db(dbName);
    const collection = db.collection(collectionName);
    let res = await collection
      .aggregate([
        {
          $group: {
            _id: "$Model",
            Extras: { $push: "$Extras" },
            Avg: { $avg: { $size: "$Extras" } },
          },
        },
        {
          $project: {
            _id: 0,
            Model: "$_id",
            CountOfExtras: {
              $size: {
                $reduce: {
                  input: "$Extras",
                  initialValue: [],
                  in: { $setUnion: ["$$value", "$$this"] },
                },
              },
            },
            Avg: "$Avg",
          },
        },
      ])
      .toArray();
    console.log(res);
  } catch (err) {
    console.log("Error in Third Query", err);
  } finally {
    client.close();
  }
};

Query 4(h)

//Query 4
lowestValPerManufacturer = async () => {
  const client = await MongoClient.connect(url, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).catch((err) => console.log("Could not connect to MongoDB", err));

  try {
    const db = client.db(dbName);
    const collection = db.collection(collectionName);

    const res = await collection
      .aggregate([
        {
          $group: {
            _id: "$Manufacturer",
            price: {
              $min: {
                $add: ["$Price", "$Milage"],
              },
            },
          },
        },
        {
          $project: {
            _id: 0,
            Manufacturer: "$_id",
            LowestPrice: "$price",
          },
        },
      ])
      .toArray();
    console.log(res);
  } catch (err) {
    console.log("Error in Fourth Query", err);
  } finally {
    client.close();
  }
};

// To execute one query comment the others.

async function run() {
  await numberOfColoursByManufacturer();
  //await extrasByManufacturer();
  //await countNumberOfExtras();
  //await lowestValPerManufacturer();
}

run();

435 views0 comments

Comments


bottom of page