Question

In: Computer Science

MONGODB Question (Similar to JSON) NOSQL QUESTION 1. Describe a scenario and write a query that...

MONGODB Question (Similar to JSON) NOSQL QUESTION

1. Describe a scenario and write a query that uses any two of these functions: $concat, $substr, $toLower, $toUpper

2. Describe a scenario and write a query that uses any two of these functions: $add, $divide, $mod, $multiply, $subtract

3. Describe a scenario and write a query that uses $redact, $$descend and $$prune command

Solutions

Expert Solution

Answer 1:

Scenario:

Consider a student collection that has the following documents.

{ "student_id" : 1, "name" : "ABC1", date: "19Q1", "description" : "passed" }
{ "student_id" : 2, "name" : "ABC2", date: "20Q2", "description" : "passed" }
{ "student_id" : 3, "name" : "ABC3", date: "18Q3", "description" : null }

$substr:

It returns a substring of a string. It has the following syntax:

{ $substr: [ <string>, <start>, <length> ] }

Using this expression to separate the date value into a year and a quarter:

db.student.aggregate(
   [
     {
       $project:
          {
            name: 1,
            yearSubstring: { $substr: [ "$date", 0, 2 ] },
            quarterSubtring: { $substr: [ "$date", 2, -1 ] }
          }
      }
   ]
)

The expression returns the following results:

{ "student_id" : 1, "name" : "ABC1", "yearSubstring" : "19", "quarterSubtring" : "Q1" }
{ "student_id" : 2, "name" : "ABC2", "yearSubstring" : "20", "quarterSubtring" : "Q2" }
{ "student_id" : 3, "name" : "XYZ1", "yearSubstring" : "18", "quarterSubtring" : "Q3" }

$concat:

It concatenates strings. It has the following syntax:

{ $concat: [ <expression1>, <expression2>, ... ] }

Using this expression to concatenate the name field and the description field with a ” - ” delimiter.

db.student.aggregate(
   [
      { $project: { nameDescription: { $concat: [ "$name", " - ", "$description" ] } } }
   ]
)

The expression returns the following results:

{ "student_id" : 1, "nameDescription" : "ABC1 - passed" }
{ "student_id" : 2, "nameDescription" : "ABC2 - passed" }
{ "student_id" : 3, "nameDescription" : null }

Answer 2:

Scenario:

Consider an employee collection with the following documents:

{ "emp_id" : 1, "project" : "A", "hours" : 80, "tasks" : 7, "salary" : 10000, "tax" : 1000 }
{ "emp_id" : 2, "project" : "B", "hours" : 40, "tasks" : 4, "salary" : 20000, "tax" : 2000 }

$mod:

It divides one number by another and returns the remainder. It has the following syntax:

{ $mod: [ <expression1>, <expression2> ] }

Using this expression to return the remainder of the hours field divided by the tasks field:

db.employee.aggregate(
   [
     { $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
   ]
)

The expression returns the following results:

{ "emp_id" : 1, "remainder" : 3 }
{ "emp_id" : 2, "remainder" : 0 }

$subtract:

It subtracts two numbers to return the difference. It has the following syntax:

{ $subtract: [ <expression1>, <expression2> ] }

Using this expression to compute the total salary in hand by subtracting the tax from the salary.

db.employee.aggregate( [ { $project: { emp_id: 1, salary_in_hand: { $subtract: [ "$salary", "$tax" ] } } } ] )

The expression returns the following results:

{ "emp_id" : 1, "salary_in_hand" : 9000 }
{ "emp_id" : 2, "salary_in_hand" : 18000 }

Answer 3:

Scenario:

Consider a forecast collection that contains documents where the tags field lists the different access values for that document/embedded document level; i.e. a value of [ "R", "W" ] specifies either "R" or "W" can access the data.

$redact:

It restricts the contents of the documents based on information stored in the documents themselves. The syntax is:

{ $redact: <expression> }

$$DESCEND:

It is a system variable and $redact returns the fields at the current document level, excluding embedded documents.

$$PRUNE:

It is a system variable and $redact excludes all fields at this current document/embedded document level.

{
  _id: 1,
  title: "123 Department Report",
  tags: [ "R", "W" ],
  year: 2014,
  subsections: [
    {
      subtitle: "Section 1: Overview",
      tags: [ "X", "R" ],
      content:  "Section 1: This is the content of section 1."
    },
    {
      subtitle: "Section 2: Analysis",
      tags: [ "W" ],
      content: "Section 2: This is the content of section 2."
    },
    {
      subtitle: "Section 3: Budgeting",
      tags: [ "A" ],
      content: {
        text: "Section 3: This is the content of section3.",
        tags: [ "X" ]
      }
    }
  ]
}

A user has access to view information with either the tag "R" or "W". To run a query on all documents with year 2014 for this user, include a $redact stage as in the following:

var userAccess = [ "R", "W" ];
db.forecasts.aggregate(
   [
     { $match: { year: 2014 } },
     { $redact: {
        $cond: {
           if: { $gt: [ { $size: { $setIntersection: [ "$tags", userAccess ] } }, 0 ] },
           then: "$$DESCEND",
           else: "$$PRUNE"
         }
       }
     }
   ]
);

The expression returns the following “redacted” document:

{
  "_id" : 1,
  "title" : "123 Department Report",
  "tags" : [ "R", "W" ],
  "year" : 2014,
  "subsections" : [
    {
      "subtitle" : "Section 1: Overview",
      "tags" : [ "X", "R" ],
      "content" : "Section 1: This is the content of section 1."
    },
    {
      "subtitle" : "Section 2: Analysis",
      "tags" : [ "W" ],
      "content" : "Section 2: This is the content of section 2."
    }
  ]
}

Related Solutions

Question: Write a single SQL query that, for each pair of actors, lists their two actor_ids...
Question: Write a single SQL query that, for each pair of actors, lists their two actor_ids and the number of films in which both actors appeared. DATABASE SCHEMA CREATE TABLE actor ( actor_id INTEGER, first_name TEXT, last_name TEXT); CREATE TABLE film ( film_id INTEGER, title TEXT, description TEXT, length INTEGER); CREATE TABLE film_actor ( actor_id INTEGER, film_id INTEGER);
1. Write a query in SQL to find the full name of the “Actors” who appeared...
1. Write a query in SQL to find the full name of the “Actors” who appeared in the movie titled Star Wars (using JOIN ). 2.Write a SQL query to find the movie Title that has received Lowest rating from reviewers, but whose actors have received an award for their contribution in movie. (Expected Output: Fantastic Beasts and Where to Find Them) 3.Write a SQL query that display the list of genres, Number of movies in that genre grouped by...
1. For each of the following, write a single SELECT query against the TSQLV4 database that...
1. For each of the following, write a single SELECT query against the TSQLV4 database that returns the result set described. Each of these queries involves two tables and can be written using a join operation. a. One row for each order shipped to France or Germany, showing the order ID, the last name of the employee for the order, and the customer ID for the order. b. One row for each employee who handled orders to Belgium, showing the...
1: Use the customers table inside of the salesordersexample database, and write a query statement to...
1: Use the customers table inside of the salesordersexample database, and write a query statement to show records from the CustFirstName, CustLastName, and CustCity columns. 2:  Use the employees table inside of the salesordersexample database, and write a query statement to show the employee’s EmployeeID, EmpFirstName, EmpLastName, and EmpPhoneNumber, if the employee is living in the 98413 zip code. 3. Use INNER JOIN to create a query result. In this query result, list each vendor’s name and the name of each...
Java 1. public void writeJSON(PrintStream ps) { Write the member variables in JSON format to the...
Java 1. public void writeJSON(PrintStream ps) { Write the member variables in JSON format to the given PrintStream } 2. public void writeJSON(PrintStream ps){ Write the member variables in JSON format to the given PrintStream. }
1. Write a query to: a. select data from INVOICES table as follows: Invoice date in...
1. Write a query to: a. select data from INVOICES table as follows: Invoice date in MM/DD/YYYY format Invoice Date in DD-Mon-YYYY format Invoice Total rounded to the nearest dollar Note: you can alias columns as you sit fit b. select data from VENDORS table as follows: Vendor Name Concatenate Vendor Name with the string ‘s Address Concatenate Vendor City, Vendor State and Vendor Zip Code (alias this) Your output should look like this (this is just an example of...
PostgreSQL 1. Write a query to join two tables employees and departments to display the department...
PostgreSQL 1. Write a query to join two tables employees and departments to display the department name, first_name and last_name, hire date, and salary for all managers who have more than 15 years of experience. 2. Write a query to join the employees and departments table to find the name of the employee including the name and last name, department ID and department name. 3. Write a SQL query to join three tables of employees, departments, and locations to find...
1. How do I write a query that displays the name (concatenate the first name, middle...
1. How do I write a query that displays the name (concatenate the first name, middle initial, and last name), date of birth, and age for all students? Show the age with no decimal places, and only include those students who are 21 or older. Order by age, as shown below: (Hint: Use the TRUNC function. The ages may be different, depending on the date that the query is run.) SELECT S_FIRST || ' ' || S_MI || ' '...
1. Define free water clearance – write out the formulas, make up a scenario type question...
1. Define free water clearance – write out the formulas, make up a scenario type question about free water clearance and show the work of how you solve your own question. b. what does it mean when renal clearance is high? What does it mean when free water clearance is high?
1.Write an SQL query that retrieves all pairs of suppliers who supply the same product, along...
1.Write an SQL query that retrieves all pairs of suppliers who supply the same product, along with their product purchase price if applicable. 2.Create a view SUPPLIEROVERVIEW that retrieves, for each supplier, the supplier number, the supplier name, and the total amount of quantities ordered. Once created, query this view to retrieve suppliers for whom the total ordered quantity exceeds 30. 3.Write a nested SQL query to retrieve all purchase order numbers of purchase orders that contain either sparkling or...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT