top of page

MongoDB Queries Using Nodejs



Here we will learn Mongodb Queries with the help of one example, below in the image list of all queries which we learn using nodejs:


Here Data is given in json format, if you need database file then send your request at realcode4you@gmail.com



First need to make connection with mongodb client:


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


Solution of Query 1:

//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();
  }
};


Solution of Query 2:

//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();
  }
};


Solution of Query 3:

//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();
  }
};


Solution of Query 4:

//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();


Send your request at realcode4you@gmail.com to get instant help in mongodb project assignments.

Here you can also get help in:

  • NodeJs Project Help Using MongoDB

  • MongoDB Basic to Advance level Queries

  • MongoDB Assignment Help

  • MongoDB Project Help

  • MongoDB Homework Help

Comments


bottom of page