0% found this document useful (0 votes)
8 views33 pages

Information Retrieval System

The document outlines key features of ReactJS and React Native, emphasizing their component-based architecture, performance through virtual DOM, and cross-platform capabilities. It also discusses ES6 features such as arrow functions, classes, template literals, and destructuring, which enhance JavaScript's functionality. Additionally, it covers state management in React class components, including the use of setState for dynamic updates.

Uploaded by

shuklasunny1324
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)
8 views33 pages

Information Retrieval System

The document outlines key features of ReactJS and React Native, emphasizing their component-based architecture, performance through virtual DOM, and cross-platform capabilities. It also discusses ES6 features such as arrow functions, classes, template literals, and destructuring, which enhance JavaScript's functionality. Additionally, it covers state management in React class components, including the use of setState for dynamic updates.

Uploaded by

shuklasunny1324
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
You are on page 1/ 33

### **ReactJS – Features (5 Marks)**

ReactJS is a popular JavaScript library developed by Facebook for


building dynamic and high-performing user interfaces. Its key
features include:

1. **JSX (JavaScript XML)**:


JSX is a syntax extension for JavaScript that looks similar to
HTML/XML. It allows developers to write HTML structures in the
same file as JavaScript code, making the code easier to understand
and debug.

2. **Components**:
React is based on a component-based architecture. Each UI part is a
component with its own logic and state. These components are
reusable and help in building large-scale applications with modular
code.

3. **One-way Data Binding (Props)**:


React follows unidirectional data flow. Data flows from parent to
child components via props. This ensures better control,
predictability, and easier debugging. React promotes immutability,
meaning data should not be directly modified.

4. **Virtual DOM**:
React uses a virtual representation of the real DOM. When changes
occur, it compares the new virtual DOM with the previous one (using
a diffing algorithm) and updates only the changed parts in the real
DOM, improving performance.

5. **Performance and Simplicity**:


Due to virtual DOM and component reusability, React apps are fast
and efficient. JSX and the component structure make React simple to
learn, use, and maintain, even for large-scale projects.
Here's a **simplified 5-mark answer** on **React Native** in easy
language, perfect for school or college exams:

---

### **React Native – (5 Marks, Simple Language)**

**React Native** is an open-source JavaScript framework used to


build mobile apps for **Android**, **iOS**, and **Windows**
using just JavaScript. It is similar to ReactJS but uses **native mobile
components** instead of web components. It helps create apps that
work on different platforms using a single codebase.

#### ✅ **Advantages of React Native:**

1. **Cross-Platform Support**:
You can write the code once and use it on both Android and iOS –
“Learn once, write anywhere”.

2. **Good Performance**:
React Native apps are fast because the code is converted into native
code that runs directly on the device.

3. **Uses JavaScript**:
If you know JavaScript, you can build mobile apps easily without
learning separate languages for iOS or Android.

4. **Large Community**:
There are many developers using React Native, so it’s easy to get
help and find solutions.

5. **Live & Hot Reloading**:


You can see the changes in your app instantly when you update the
code.
❌ **Disadvantages of React Native:**

1. **Still New**:
React Native is still developing and may not support all mobile
features.

2. **Less Secure**:
It’s not the best choice for apps that need strong security, like
banking apps.

3. **Slow Startup**:
React Native apps may take longer to start on some devices.

Architecture of the React Application


React library is just UI library and it does not enforce any particular
pattern to write a complex application. Developers are free to choose
the design pattern of their choice. React community advocates certain
design pattern. One of the patterns is Flux pattern. React library also
provides lot of concepts like Higher Order component, Context,
Render props, Refs etc., to write better code. React Hooks is evolving
concept to do state management in big projects. Let us try to
understand the high level architecture of a React application.
• React app starts with a single root component.
• Root component is build using one or more component.
• Each component can be nested with other component to any level.
• Composition is one of the core concepts of React library. So, each
component is build by composing smaller components instead of
inheriting one component from another component.
• Most of the components are user interface components.
• React app can include third party component for specific purpose
such as routing, animation, state management, etc.
ES6 INTO

1. let and const


let and const are block-scoped variables introduced in ES6.

let: Allows reassignment, but cannot be redeclared in the same


scope.
const: Must be initialized and cannot be reassigned or redeclared.

Example:
let a = 10;
a = 20; // valid

const b = 30;
b = 40; // ❌ TypeError
Use const by default and let only when reassignment is necessary.

2. Arrow Functions
Here’s a **5-mark answer** summarizing **Arrow Functions in
ES6** clearly and concisely:

### **Arrow Functions (ES6)**

Arrow functions were introduced in ES6 to simplify function syntax


and make code more concise and readable. They are always
expressions and provide a shorter way to write anonymous functions.

**Syntax:**

```javascript
let functionName = (arg1, arg2, ..., argN) => {
// statements
}
```

* **Single-line return:**

```javascript
let sum = (a, b) => a + b;
```

#### **Examples:**

1. **No arguments:**
let greet = () => console.log("Hello");

2. **One argument (parentheses optional):**


let greet = name => console.log(name);

3. **Multi-line function:**
let sum = (a, b) => {
let result = a + b;
return result;
}

4. **Conditional use:**
let age = 10;
let welcome = (age < 18) ? () => console.log("Kid") : () =>
console.log("Adult");
welcome();

#### **Key Points:**

* No `function` or `return` keyword is needed for single-expression


returns.
* `this` is lexically bound (unlike traditional functions).
* Useful for callbacks, array methods, and cleaner code structure.

**Note:** Arrow functions cannot be used as constructors and do


not have their own `this`, `arguments`, or `super`.

✅ ES6 Classes – Simple Explanation with Example


In ES6, class is a new way to write constructor functions and manage
object-oriented programming in JavaScript. It’s a cleaner and more
intuitive syntax for creating objects and handling inheritance.

🔹 Basic Syntax:
class ClassName {
constructor(parameters) {
// initialization code
}

methodName() {
// method logic
}
}

🔧 Simple Example:
// Define a class
class Student {
constructor(name, grade) {
this.name = name;
this.grade = grade;
}

displayInfo() {
console.log(`Student Name: ${this.name}, Grade: ${this.grade}`);
}
}

// Create an object (instance)


const student1 = new Student("Sneha", "6th");

// Call method
student1.displayInfo();
// Output: Student Name: Sneha, Grade: 6th

4) Template Literals
Template literals (template strings) provide the ability to create single
and multi-line strings with variables between them.
ES6 introduced a new way of creating strings called “template
literals”. Template literals are enclosed in backtick (` ` ) characters
instead of quotes (‘ ‘ or ” “), and can contain placeholders, which are
denoted by a dollar sign followed by curly braces (${expression}).

Syntax:
${ expression }

Example:

let total = 100


let product = 'Dell laptop'
let message = `The price for product ${product} is ${total}
Thank you.`

5) Spread operator
Spread operator … allows spreading(actual copy not just a reference)
of elements in an iterable collection (array or string) to individual
elements and function parameters.
Syntax:
...obje_name
Example:
let params = ['name', 'age']
let fullParams = ['device', 'location', ...params]
// Output: ['device', 'location', 'name', 'age']

let obj = {name:'bob', age:20}

let newObj = {height: 6, ...obj}


// Output: {height: 6, name: 'bob', age: 20}

6) Rest operator
The rest operator allows a function to accept an indefinite number
of arguments as an array. It is helpful when you don't know in
advance how many arguments will be passed.
It collects the remaining (or "rest") arguments into a single array
parameter
Syntax:
The rest operator is denoted by three dots (...) as a prefix followed by
the name of the parameter.
function fname(a,b,...myRest) {
//statements
}

Example:
let display = (...args) =>
{
let sum = 0;
for (let i of args) {
sum += i;
}
console.log("Sum = "+sum);
}

display(10,10,10,10);

Destructuring
Destructuring is a convenient way of creating new variables by
extracting some values from data stored in objects or arrays.
Destructuring can be used when we may have an array or object that
we are working with, but we only need some of the items contained in
these.
This allows developers to extract values from an object and assign
them to variables with a more concise syntax.

Using Object
let person = {a:10, b:20, c:30}
let {a, b} = person;
console.log(a, b)

Using Array
let z = [50, 60,30]
let [x,y] = z;
console.log(x, y)

Rest Parameters and Destructuring


 Destructuring means to break down a complex structure into
simpler parts. We can define an array as the rest parameter. The
passed-in arguments will be broken down into the array. Rest
parameter supports array destructuring only.
 By using the rest parameter, we can put all the remaining
elements of an array in a new array.

var colors = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange",


"Red"];

// destructuring assignment
var [a,b,...args] = colors;
console.log(a);
console.log(b);
console.log(args);

11) Parameter context matching


We can use the same concepts as before to get the values from objects
and arrays into parameters.

Using array parameter

let getParameterFromArray = ( [a, b, c] ) =>


{
console.log(a,b,c)
}
getParameterFromArray([5,6,7,8,9])
// Output: 567

Using object parameter

let getParameterFromObject= ( {name, age }) => {


console.log(name, ' ', age)
}
getParameterFromObject({name: 'ABC', age: 20, height: 6.0})
// Output: ABC 20

ES6 Modules (Import & Export)


In ES6, every JavaScript file is treated as a module. Data inside a
module is private by default. To access it from another file, we must
export and import it.

🔹 1. Named Export
 Use when exporting multiple values.
 Must import using exact names.
👉 Export:
// utils.js
export const temp1 = "Hello";
export const temp2 = "World";
👉 Import:
import { temp1, temp2 } from './utils';

🔹 2. Default Export
 Only one default export per file.
 Can import using any name.
👉 Export:
// user.js
const user = { name: "Alice" };
export default user;
👉 Import:
import anyName from './user';

🔹 3. Default + Named Exports Together


// constants.js
export const PI = 3.14;
export const AGE = 25;
const NAME = "Bob";
export default NAME;
// Importing
import NAME, { PI, AGE } from './constants';

🔹 4. Import All as an Object


import * as constants from './constants';

console.log(constants.PI);
console.log(constants.default); // default export

🔸 Other Notes:
 ❌ export default const age = 25; → Invalid
 ✅ Instead:
const age = 25;
export default age;

🔹 Combined Export
const PI = 3.14;
const AGE = 20;
const USERNAME = "ABC";
const USER = { name: "XYZ", age: 30 };

export { PI, AGE, USERNAME, USER as default };


import USER, { PI, AGE, USERNAME } from "./constants";

States

In React class components, state is an object that holds dynamic data and determines
how the component behaves and renders. It's initialized in the constructor using
this.state, and updated using this.setState(). Updating the state triggers re-rendering
of the component, ensuring the UI reflects the latest data.
1. Creating State in a Class Component
In class components, state is initialized inside the constructor using this.state.
🔹 Example:
jsx
CopyEdit
import React, { Component } from 'react';
class Welcome extends Component {
constructor(props) {
super(props);

// Initializing state
this.state = {
message: 'Welcome to React!'
};
}

render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
);
}
}

export default Welcome;


🔸 The message state is created and initialized inside the constructor.

✅ 2. Updating State Using setState()


We use this.setState() to update the value of any state variable. React then re-
renders the component.
🔹 Example with a Button to Update State:
jsx
CopyEdit
import React, { Component } from 'react';

class Welcome extends Component {


constructor(props) {
super(props);
this.state = {
message: 'Welcome to React!'
};
}

changeMessage = () => {
this.setState({ message: 'Thanks for visiting!' }); // updating state
}

render() {
return (
<div>
<h1>{this.state.message}</h1>
<button onClick={this.changeMessage}>Click Me</button>
</div>
);
}
}

export default Welcome;

setState()
🔹 setState() in React – Easy Explanation with Examples
In React class components, setState() is a method used to update
the state of a component. When you call setState(), React merges the
new state with the existing one and re-renders the component.

🔸 Syntax:
this.setState({ key: newValue });
Or using a function for previous state dependent logic:
this.setState((prevState) => ({
key: prevState.key + 1
}));

✅ Example 1: Simple setState Usage


import React, { Component } from 'react';

class Counter extends Component {


constructor() {
super();
this.state = {
count: 0
};
}

increment = () => {
this.setState({ count: this.state.count + 1 }); // Simple update
}

render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

export default Counter;

✅ Example 2: setState with Previous State


increment = () => {
this.setState((prevState) => ({
count: prevState.count + 1
}));
};
🔹 This is safer when the next state depends on the previous one,
especially in async cases.

🔸 Things to Remember
 setState() is asynchronous – don’t immediately rely on updated
state after calling it.
 React batches multiple setState() calls for performance.
 You can also update part of the state – it merges with the old
state.

🔸 Example: Update Multiple Keys in State


this.setState({
name: 'Sneha',
age: 22
});
✅ React Class Component — With and Without JSX
React supports two ways to write components:
1. With JSX – using HTML-like syntax inside JavaScript.
2. Without JSX – using React.createElement() manually.

🔷 1. React Class Component With JSX


This is the most common and preferred way to write React
components.
import React, { Component } from 'react';

class MyComponent extends Component {


render() {
return (
<div>
<h2>Hello JSX</h2>
<p>This is a class component using JSX.</p>
</div>
);
}
}

export default MyComponent;

🔷 2. React Class Component Without JSX


Same as above, but written using React.createElement():
import React, { Component } from 'react';

class MyComponent extends Component {


render() {
return React.createElement(
'div',
null,
React.createElement('h2', null, 'Hello without JSX'),
React.createElement('p', null, 'This is a class component without
JSX.')
);
}
}

export default MyComponent;

🔁 Comparison
Feature With JSX Without JSX
Syntax Clean, readable Verbose, nested
Usage Widely used Rare, used when not transpiling
Requires Babel? ✅ Yes ❌ No

✅ Which one should you use?


Always prefer JSX. It’s easier to read, write, and debug. Writing
without JSX is useful only in special cases (like when not using a build
tool).

Would you like a working example with state or props too?

React Class Component Lifecycle

🌱 1. Mounting Phase
When a component is being created and inserted into the DOM.
Steps in Mounting:
1. constructor()
o Initializes state and binds event handlers.
o First method called in the component lifecycle.
2. getDerivedStateFromProps()
o Static method.
o Syncs state with props when props change.
o Called before render() in both mounting and updating.
3. render()
o Returns the JSX that defines UI.
o Pure: should not change state or interact with DOM here.
4. componentDidMount()
o Invoked once component is inserted in DOM.
o Perfect for API calls, DOM manipulation, or setting up
timers.

🔁 2. Updating Phase
When props or state changes, and the component re-renders.
Triggers:
 New props
 setState()
 forceUpdate()
Steps in Updating:
1. getDerivedStateFromProps()
o Again called to update state with new props.
2. shouldComponentUpdate()
o Used to prevent unnecessary re-renders.
o Return false to stop update; true to continue.
3. render()
o UI gets re-rendered.
4. getSnapshotBeforeUpdate()
o Captures info from DOM before it's potentially changed.
o Return value is passed to componentDidUpdate().
5. React updates DOM and refs
o DOM changes are committed.
6. componentDidUpdate(prevProps, prevState, snapshot)
o Called after the DOM is updated.
o Good for making network requests based on prop/state
changes.

🗑️3. Unmounting Phase


When a component is being removed from the DOM.
Step in Unmounting:
 componentWillUnmount()
o Cleanup method.
o Ideal for clearing timers, removing event listeners, and
cancelling API calls.

import React, { Component } from 'react';

class LifecycleExample extends Component {


constructor(props) {
super(props);
console.log('1️⃣ constructor');
this.state = {
count: 0,
};
}

static getDerivedStateFromProps(props, state) {


console.log('2️⃣ getDerivedStateFromProps');
// Normally you'd compare props to state and return new state if
needed
return null; // No change to state
}

componentDidMount() {
console.log('4️⃣ componentDidMount');
// You can perform API calls or set intervals here
this.interval = setInterval(() => {
this.setState({ count: this.state.count + 1 });
}, 2000);
}

shouldComponentUpdate(nextProps, nextState) {
console.log('5️⃣ shouldComponentUpdate');
return true; // Allow update
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('6️⃣ getSnapshotBeforeUpdate');
return `Previous count: ${prevState.count}`;
}

componentDidUpdate(prevProps, prevState, snapshot) {


console.log('7️⃣ componentDidUpdate');
console.log(' Snapshot:', snapshot);
}

componentWillUnmount() {
console.log(' componentWillUnmount');
clearInterval(this.interval); // Cleanup
}

render() {
console.log('render');
return (
<div style={{ textAlign: 'center', marginTop: '50px' }}>
<h1>React Lifecycle Demo</h1>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count +
1 })}>
Increment Manually
</button>
</div>
);
}
}

export default LifecycleExample;

App.js with:
jsx
Copy code
import React from 'react';
import LifecycleDemo from './LifecycleDemo';

function App() {
return (
<div className="App">
<LifecycleDemo />
</div>
);
}

export default App;

📌 Event Handling in React using bind Keyword (Illustrated)


In React class components, we use the bind() method to explicitly
bind the value of this to the event handler method. This ensures that
this inside the method refers to the component instance.

✅ Why bind is used?


By default, this is undefined in event handler methods unless we
explicitly bind it to the component.

🔧 Syntax
this.methodName = this.methodName.bind(this);

🧪 Example: Event Handling using bind


import React, { Component } from 'react';

class ClickHandler extends Component {


constructor(props) {
super(props);
this.state = {
message: "Hello"
};

// Binding 'this' to the handler


this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState({ message: "You clicked the button!" });
}

render() {
return (
<div>
<h2>{this.state.message}</h2>
<button onClick={this.handleClick}>Click Me</button>
</div>
);
}
}

export default ClickHandler;

📝 Output:
Initially displays: Hello
After clicking the button: You clicked the button!

HOOKS IN FUNCTIONAL COMPONENT

useState Hook
The useState hook is a built-in React hook that allows you to add
React state to functional components. It takes the initial state as an
argument and returns an array of two entries. The first entry is the
current state, and the second one is a function that allows you to
update it.
Introduced in React 16.8, the useState hook offers a way to add state
to functional components. It returns a stateful value and a function
to update it.

Syntax
const [state, setState] = useState(initialState)

state: It is the value of the current state.


setState: It is the function that is used to update the state.
initialState: It is the initial value of the state.

import React, { useState } from 'react';


const Count1 = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Count1

In this example, useState is called with an argument of 0 to set the


initial state. useState returns an array that contains the current state
(count) and a function (setCount) to update it. This pattern is known
as "array destructuring".

What is useReducer Hook?


The useReducer hook is used for state management in React
functional components. It is an alternative to useState, and is
especially useful when:
 State logic is complex (e.g., multiple related values).
 The next state depends on the previous state.
 You want to group state logic in a central reducer function.

✅ Syntax
javascript

const [state, dispatch] = useReducer(reducerFunction, initialState);


 state: Current state value.
 dispatch: Function used to send actions to update the state.
 reducerFunction: A function that takes current state and an
action, then returns new state.
 initialState: The initial state value.
💡 Simple Example: Counter using useReducer
jsx
Copy code
import React, { useReducer } from 'react';

// 1️⃣ Reducer Function


function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
return state;
}
}
// Functional Component
function Counter() {
// useReducer Hook
const [state, dispatch] = useReducer(reducer, { count: 0 });

return (
<div>
<h2>Count: {state.count}</h2>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
}

export default Counter;


MONODB
Sure! Here's a concise and well-structured 5-mark answer each for:

✅ 1. Collection in MongoDB (5 Marks)


A Collection in MongoDB is similar to a table in relational databases. It is a group of
documents stored within a database.
✅ Key Features:
 Schema-less: Documents within a collection do not need to have the same
structure (fields and types).
 Part of a database: A single MongoDB database can contain multiple
collections.
 Dynamic creation: A collection is created automatically when the first
document is inserted.
✅ Syntax Example:
db.authors.insertOne({ name: "Ankita" })
Here, authors is the collection name, and the inserted object is a document.
✅ Naming Rules:
 Must begin with a letter or underscore (_)
 Cannot begin with a number or contain $, null characters, or start with system.
 Max length is 120 bytes (including database name).

✅ 2. Document in MongoDB (5 Marks)


A Document in MongoDB is a single record in a collection, stored in BSON (Binary
JSON) format. It is made up of field-value pairs.
✅ Key Features:
 Fields can be of any BSON type (e.g., string, number, array, object).
 MongoDB preserves the field order, except _id which comes first.
 Max document size is 16MB.
✅ Syntax Example:
{
_id: ObjectId("123..."),
title: "MongoDB Basics",
author: "John Doe",
year: 2025
}
✅ _id Field:
 Every document must have a unique _id.
 Can be auto-generated (ObjectId) or user-defined.
 Acts like a primary key.
✅ Naming Rules:
 Field names must be strings
 Cannot contain null characters or start with $
 _id is reserved and must be unique
Sure! Here's a simple and clear explanation of how arrays can be modified in
MongoDB, with examples using common operators:

✅ Modifying Arrays in MongoDB


In MongoDB, arrays in documents can be modified using update operators like
$push, $addToSet, $pop, $pull, and $pullAll.
🔹 1. $push — Adds an element to an array
Adds a new element to the end of the array.
Example:
db.students.updateOne(
{ name: "Sneha" },
{ $push: { subjects: "Science" } }
)
✅ If subjects is ["Math", "English"], it becomes ["Math", "English", "Science"].

🔹 2. $addToSet — Adds only if not present


Prevents duplicates when adding an element.
Example:
db.students.updateOne(
{ name: "Sneha" },
{ $addToSet: { subjects: "Math" } }
)
✅ If "Math" is already there, it won’t be added again.

🔹 3. $pop — Removes the first or last element


Removes from array:
 1 = last
 -1 = first
Example (remove last):
db.students.updateOne(
{ name: "Sneha" },
{ $pop: { subjects: 1 } }
)

🔹 4. $pull — Removes matching element(s)


Deletes all matching values from array.
Example:
db.students.updateOne(
{ name: "Sneha" },
{ $pull: { subjects: "English" } }
)
✅ All "English" values are removed from subjects array.

🔹 5. $pullAll — Removes multiple values


Removes all instances of specific values.
Example:
db.students.updateOne(
{ name: "Sneha" },
{ $pullAll: { subjects: ["Math", "Science"] } }
)

📌 Sample Document Before:


{
name: "Sneha",
subjects: ["Math", "English", "Science"]
}

Sure! Here's a well-explained version of MongoDB Update Modifiers with some


basic info, syntax, and examples, all in a clean format for easy understanding.

🛠️MongoDB Update Modifiers — Explained with Syntax & Examples


MongoDB update modifiers are special operators used to modify fields of documents
in a collection. They allow you to update, add, remove, or manipulate field values
without replacing the entire document.

🔹 1. $set – Set a specific field’s value


Purpose: Add a new field or update the value of an existing field.
Syntax:
db.collection.updateOne({ criteria }, { $set: { field: value } })
Example:
db.students.updateOne(
{ name: "Amit" },
{ $set: { grade: "A" } }
)
✅ This sets grade to "A" in the document where name is "Amit".

🔹 2. $inc – Increment (or decrement) a numeric field


Purpose: Increase or decrease a number field’s value.
Example:
db.students.updateOne(
{ name: "Amit" },
{ $inc: { marks: 5 } }
)
✅ Increments marks by 5.

🔹 3. $unset – Remove a field from the document


Purpose: Deletes a field completely from the document.
Example:
db.students.updateOne(
{ name: "Amit" },
{ $unset: { grade: "" } }
)
✅ Removes the grade field from the document.

🔹 4. $rename – Rename a field


Purpose: Change the name of an existing field.
Example:
db.students.updateOne(
{},
{ $rename: { "grade": "finalGrade" } }
)
✅ Renames the grade field to finalGrade.

🔹 5. $mul – Multiply a field's value


Purpose: Multiply the value of a numeric field by a specific number.
Example:
db.products.updateOne(
{ item: "Pen" },
{ $mul: { price: 2 } }
)
✅ Doubles the value of price.

🔹 6. $min – Set value only if it is less than the current value


Example:
db.students.updateOne(
{ name: "Amit" },
{ $min: { marks: 60 } }
)
✅ Will update marks to 60 only if current value is more than 60.

🔹 7. $max – Set value only if it is greater than the current value


Example:
db.students.updateOne(
{ name: "Amit" },
{ $max: { marks: 95 } }
)
✅ Will update marks to 95 only if current value is less than 95.

📄 Sample Document Before:


{
name: "Amit",
marks: 85,
grade: "B",
price: 10
}

🧪 After Applying Update Modifiers:


{
name: "Amit",
marks: 90, // after $inc or $max
finalGrade: "B", // after $rename
price: 20 // after $mul
}
?

Sure! Here's a simple and clear explanation of sort and slice operations in MongoDB,
with syntax and examples:

🔢 sort in MongoDB
Purpose: To order documents returned from a query, based on one or more fields.
✅ Syntax:
db.collection.find().sort({ field: 1 }) // ascending order
db.collection.find().sort({ field: -1 }) // descending order
✅ Example:
db.students.find().sort({ marks: -1 })
📌 This returns all students sorted in descending order of marks.

✂️slice in MongoDB
Purpose: To return a subset of array elements from an array field.
✅ Syntax (used inside projection):
db.collection.find({}, { arrayField: { $slice: n } }) // first n elements
db.collection.find({}, { arrayField: { $slice: -n } }) // last n elements
db.collection.find({}, { arrayField: { $slice: [skip, limit] } }) // custom range
✅ Example Document:
{
name: "Ravi",
scores: [85, 78, 92, 88, 76]
}
✅ Examples of Slice:
db.students.find({ name: "Ravi" }, { scores: { $slice: 3 } })
📌 Returns the first 3 scores: [85, 78, 92]
db.students.find({ name: "Ravi" }, { scores: { $slice: -2 } })
📌 Returns the last 2 scores: [88, 76]
db.students.find({ name: "Ravi" }, { scores: { $slice: [1, 3] } })
📌 Returns 3 elements starting from index 1: [78, 92, 88]

🔁 Combine with Find


You can combine find, sort, and limit together:
db.students.find().sort({ marks: -1 }).limit(5)
📌 Returns top 5 students with highest marks.

You might also like