tag:blogger.com,1999:blog-10558666550419597952024-03-14T05:31:02.780+05:30TechHeapTutorials and examples on various frameworks and web developmentUnknownnoreply@blogger.comBlogger87125tag:blogger.com,1999:blog-1055866655041959795.post-34882883570196113402022-08-26T21:48:00.006+05:302022-08-26T21:48:58.405+05:30Mutiple ways to programmatically navigate using React router<p> Mutliple ways to navigate between pages in react using react router. </p><p></p><ul style="text-align: left;"><li>React Router v6</li></ul><div><span> </span><span> </span><span> </span>useNavigate hook can be used.<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; overflow-wrap: normal; word-wrap: normal;">
import { useNavigate } from "react-router-dom"
const Component = () => {
<span> </span>let navigate = useNavigate();
<span> </span>navigate("/pathname", state: { someData });
}
</code><br /></pre>
</div><ul style="text-align: left;"><li>React Router v5</li></ul><div><span> </span><span> </span><span> useHistory hook can be used.</span>
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; overflow-wrap: normal; word-wrap: normal;">
import { useHistory } from "react-router-dom"
const Component = () => {
<span> </span>let history = useHistory();
<span> </span>history.push("/pathname");
}
</code><br /></pre>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-23775145046154483952021-06-24T13:20:00.001+05:302021-06-24T13:20:13.618+05:30React JS Interview Questions and topics<p> To evaluate a candidate, recruiters generally asks certain questions so that they can know how much the candidate has hands-on experience and how much is his/her technical capabilities. Below are some of the questions:</p><ul style="text-align: left;"><li>What is Virtual DOM?</li><li>Explain how React Routing works?</li><li>What are the ways to debug React JS application?</li><li>What are the libraries needed for unit testing. Write a sample unit test.</li><li>How to configure application so that whenever an user commits code, it first checks the code alignments and other lint issues and fix them automatically.</li><li>How to configure application so that whenever user pushes code to source control, it first run all unit test cases and on success only it pushes the code to the repo</li><li>What is Responsize web design?</li><li>How does Exception Handling works,</li><li>What type of configuration needed to deploy an react application on mulitple environments.</li><li>How to maintain configuration data like API URLs, API Keys etc based on different environments in application.</li><li>Difference between const and let. Write an example.</li><li>Difference between == and ===, write an example.</li><li>what is use of pre commit and post commit in package.json?</li><li>Difference between ES6 functions like filter and find.</li><li>How to configure redux in the application.</li><li>How to access lifecycle methods in functional components.</li><li>Which lifecycle methods we can access using useEffect hook.</li><li>How and where we can use Spread Operator?</li><li>What is the use of JWT token and how does it works.</li><li><br /></li></ul>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-90225896623792652692021-06-18T10:44:00.007+05:302021-06-18T10:55:22.442+05:30How to query like joins on 2 collections in mongodb using aggregate keyword<div dir="ltr" style="text-align: left;" trbidi="on">
To query like JOINS between 2 collections in mongodb, we need to use $aggregate.<br />
<br />
Lets see the example:</div><div dir="ltr" style="text-align: left;" trbidi="on">
<br />I have 2 collections, one is Employee and another one is Department.<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; overflow-wrap: normal; word-wrap: normal;"> Employee Collection
{
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"departmentId" : 2
},
{
"_id" : 2,
"name" : {
"first" : "Abc",
"last" : "Agrawal"
},
<span> </span>"departmentId" : 1
},
{
"_id" : 3,
"name" : {
"first" : "Dhruv",
"last" : "Agrawal"
},
"departmentId" : 1,
}
}
<pre style="background-attachment: initial; background-clip: initial; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: 1px dashed rgb(204, 204, 204); font-family: arial; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 677.156px;"><code style="overflow-wrap: normal; word-wrap: normal;">Department Collection
{
"_id" : 1,
"name" : "finance"
},
{
"_id" : 2,
"name" : "hr"
}
} </code></pre>
</code></pre>
<br />
Now I need to fetch employee details for id 2 along with employee's department name. <br />
<br />
The query would be:<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; overflow-wrap: normal; word-wrap: normal;">
db.employee
.aggregate([
{ $match: { _id: 2 } },
{
$lookup: {
localField: 'departmentId',
from: 'department',
foreignField: '_id',
as: 'departmentName',
},
},
{ $unwind: '$departmentName' }<br /> ]).toArray()
</code></pre>
<br />
The output would be:<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 646.469px;"><code style="overflow-wrap: normal; word-wrap: normal;">
{
"_id" : 2,
"name" : {
"first" : "Abc",
"last" : "Agrawal"
},
"departmentName": {
"name": "finance"
}
</code></pre>
<br /></div><div dir="ltr" style="text-align: left;" trbidi="on">Hope it helps.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-9039538662530106422019-10-30T16:15:00.001+05:302019-10-30T16:15:57.985+05:30How to mock third party libraries and functions in jest using react js<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
Jest is a library we use for testing JS code whether it's an Angular application or React JS.<br />
<br />
Many times we encounter issues while testing code which has third party libraries like mixpanel, moment, redux etc.<br />
<br />
To resolve, we need to mock these 3rd party libraries and their respective functions. We need to intercept these libraries by mocking as given below:<br />
<br />
1) Create a directory at root as <b>"__mocks__"</b>.<br />
2) Let say we need to create mock for <b>moment</b> library. Create a JS file under __mocks__ as <b>moment.js</b>. Keep in mind to have the file name exactly same as declared when importing in source code.<br />
3) Open moment.js file and write below code snippet<br />
<br />
<div>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">const moment = {
anyFunc: jest.fn()
}
export default moment;
</code></pre>
</div>
<br />
4) Now execute your jest test cases. It will not throw error for moment library.<br />
5) Use can add any mock functions in that file and add expected response and test them.<br />
<br />
Hope this helps!<br />
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-67391022698937340342019-07-23T17:06:00.003+05:302021-06-24T13:22:18.238+05:30How to add a checkbox in primereact datatable<div dir="ltr" style="text-align: left;" trbidi="on">
Code snippet to add a checkbox in each row of a primereact datatable.<br />
<br />
<div>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">import React, { Component } from 'react';
import {DataTable} from 'primereact/datatable';
import {Column} from 'primereact/column';
export class DTColumnCheckBoxDemo extends Component {
constructor() {
super();
this.state = {
}
}
render() {
return (
<DataTable value={this.state.list}}
selection={this.state.listItem} onSelectionChange={(e) => this.setState({listItem: e.data})} >
<Column em="" selectionmode="multiple" />
<Column field="xyz" header="XYZ" />
<Column field="abc" header="ABC" />
</DataTable>
);
}
</code></pre>
</div>
<br />
In Column tag we need to add selectionmode attribute to add checkbox in datatable.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-275065645051951222019-07-05T13:08:00.004+05:302021-06-24T13:23:08.590+05:30How to host React JS code with Spring Boot Application<div dir="ltr" style="text-align: left;" trbidi="on">
Sometimes we got a requirement where we need to configure react application so that it can be serve in Spring Boot Application. Means, both Spring boot application and react js code can be served from same server.<br />
<br />
Following are the steps we need to follow to make it happen:<br />
<ol style="text-align: left;">
<li>Put all of your <b>html, js, css, etc.</b> files to <b>src/main/resources/static</b>. Under <b>resources</b> folder create a static folder and under it paste all your frontend code. </li>
<li>Add one ResourceResolver Class to Spring as below:
<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
@Configuration
public class Config implements WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ResourceResolver resolver = new ReactResourceResolver();
registry.addResourceHandler("/**")
.resourceChain(true)
.addResolver(resolver);
}
public class ReactResourceResolver implements ResourceResolver {
// root dir of react files
private static final String REACT_DIR = "/static/";
private static final String REACT_STATIC_DIR = "static";
private Resource index = new ClassPathResource(REACT_DIR + "index.html");
private List<string> rootStaticFiles = Arrays.asList("favicon.io",
"asset-manifest.json", "manifest.json", "service-worker.js");
@Override
public Resource resolveResource(
HttpServletRequest request, String requestPath,
List locations, ResourceResolverChain chain) {
return resolve(requestPath, locations);
}
@Override
public String resolveUrlPath(
String resourcePath, List locations,
ResourceResolverChain chain) {
Resource resolvedResource = resolve(resourcePath, locations);
if (resolvedResource == null) {
return null;
}
try {
return resolvedResource.getURL().toString();
} catch (IOException e) {
return resolvedResource.getFilename();
}
}
private Resource resolve(
String requestPath, List locations) {
if (requestPath == null) return null;
if (rootStaticFiles.contains(requestPath)
|| requestPath.startsWith(REACT_STATIC_DIR)) {
return new ClassPathResource(REACT_DIR + requestPath);
} else
return index;
}
}
}
</string></code>
</pre>
</li>
</ol>
Its done. Application frontend will run as smooth.
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-70902564942549287512019-04-22T17:19:00.000+05:302019-04-22T17:19:42.789+05:30How to read and get value from Info.plist file using react native in IOS app<div dir="ltr" style="text-align: left;" trbidi="on">
Info.plist file is a very important file which handles all the configuration for an app. We can use this file to have some custom information specific to app which can be read when app is getting loaded.<br />
<br />
To read the file we need to make a bridge component that allow us to get values from the plist file. Because app cannot directly read the file until the app is developed in native language.<br />
<br />
Info.plist is having data in JSON format, which can be read as key, value pair.<br />
<br />
First, we need to create a custom class (Objective-C) that will read info.plist file and send the response back to app.<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
#import "AppConfig.h"
@interface AppConfig()
@end
@implementation AppConfig
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(getPListValue:(NSString *)param callback:(RCTResponseSenderBlock)callback)
{
NSString* paramValue = [[[NSBundle mainBundle] infoDictionary] valueForKey:param];
if(paramValue == nil)
paramValue = @"";
callback(@[[NSNull null], paramValue]);
}
@end
</code></pre>
<br />
Using NativeModules we can call this function and get the value of any keys in react native. Import NativeModules from react-native and directly call the method as below:<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
import { NativeModules } from 'react-native';
NativeModules.AppConfig.getPListValue("keyName", (error, keyValue) => {
console.log(keyValue);
});
</code></pre>
<br />
On running above code, it will log the key value for the specific key you have given in code as keyName.<br />
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-11123065441706940612019-04-22T14:44:00.002+05:302019-04-22T14:44:28.274+05:30How to add action button in notifications of an ios app using react native<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
In this tutorial, we will learn how to add an action button on local notifications triggered by application using React Native.<br />
<br />
To achieve this, we need to create a bridge component that will enable communication between react-native and IOS. Below code is in Objective-C.<br />
<br />
We call the IOS function from react native and this objective C method will create buttons and append to notifications that come on device.<br />
<br />
Below are the steps:<br />
<br />
1) Create a custom ActionNotification.m file and add below code snippet into that:<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
#import "ActionNotification.h"
@interface ActionNotification()
@end
@implementation ActionNotification
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(createUserNotificationSettings:(RCTResponseSenderBlock)callback)
{
UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
[action1 setActivationMode: UIUserNotificationActivationModeForeground];
[action1 setTitle:@"Title1"];
[action1 setIdentifier:@"first_button"];
[action1 setDestructive:YES];
[action1 setAuthenticationRequired:NO];
UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];
[action2 setActivationMode: UIUserNotificationActivationModeForeground];
[action2 setTitle:@"Title2"];
[action2 setIdentifier:@"second_button"];
[action2 setDestructive:NO];
[action2 setAuthenticationRequired:NO];
UIMutableUserNotificationCategory *actionCategory = [[UIMutableUserNotificationCategory alloc] init];
[actionCategory setIdentifier:@"actionCategory"];
[actionCategory setActions:@[action1, action2]
forContext:UIUserNotificationActionContextDefault];
NSSet *categories = [NSSet setWithObject:actionCategory];
UIUserNotificationType types = (UIUserNotificationTypeAlert|
UIUserNotificationTypeSound|
UIUserNotificationTypeBadge);
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:types categories:categories]];
callback(@[[NSNull null], @"done"]);
}
@end
</code></pre>
<br />
In above implementation, we have created one method <span style="background-color: #f0f0f0; font-family: "arial"; font-size: 12px;">createUserNotificationSettings,</span> which will add action buttons to notification. Now, this function need to be called just before scheduling the notification. Also, we need to make sure that identifier has been properly set. In above case, it must be "actionCategory".<br />
<br />
2) Add Action Button Click Event function in AppDelegate.m file.<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(nonnull UILocalNotification *)notification withResponseInfo:(nonnull NSDictionary *)responseInfo completionHandler:(nonnull void (^)())completionHandler
{
if ([identifier isEqualToString: @"first_button"]) {
NSLog(@"First notification button was pressed");
} else {
NSLog(@"Second notification button was pressed");
}
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler
{
if ([identifier isEqualToString: @"first_button"]) {
NSLog(@"First notification button was pressed");
} else {
NSLog(@"Second notification button was pressed");
}
}
</code>
</pre>
<br />
The above functions will handle action button events.<br />
<br />
3) Now, create JS file that will call IOS function just before scheduling Notifications.<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
import { PushNotificationIOS, NativeModules } from 'react-native';
NativeModules.ActionNotification.createUserNotificationSettings((error, status) => {
return status;
});
PushNotificationIOS.scheduleLocalNotification({
fireDate: new Date(),
alertBody: "hello",
category: "actionCategory" // category must match to what we have defined in create notification method in Objective-C
});
</code>
</pre>
<br />
<br />
Thats it!<br />
It should display the action button when any notification comes for that particular app.<br />
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-5814151736759873432019-04-19T10:38:00.000+05:302019-04-19T10:38:59.174+05:30How to get product key of windows OS installed on machine<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
Steps to get the product key of windows OS installed on the laptop, desktop or any other device.<br />
<br />
1) Press on Start Menu or Windows Key + X.<br />
2) Open command prompt in Admin mode.<br />
3) Enter below command:<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">wmic path SoftwareLicensingService get OA3xOriginalProductKey
</code></pre>
<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-gHR9Pl8Yg64/XLlWntnEu4I/AAAAAAAAPkc/tSHZWqX6OlQLwEiLJQc9BaYBhx-6sK7bgCLcBGAs/s1600/Capture.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="178" data-original-width="679" height="167" src="https://4.bp.blogspot.com/-gHR9Pl8Yg64/XLlWntnEu4I/AAAAAAAAPkc/tSHZWqX6OlQLwEiLJQc9BaYBhx-6sK7bgCLcBGAs/s640/Capture.PNG" width="640" /></a></div>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-87219568220115567262018-04-25T11:53:00.001+05:302018-04-25T11:53:33.516+05:30How to update password in GIT using command line<div dir="ltr" style="text-align: left;" trbidi="on">
As we know, using GIT through command line is one of the best way to handle repos. However, sometimes we faces issues when we update GIT password and command line does not take the updated password automatically.<br />
<div>
<br /></div>
<div>
To fix this issue, we can use the below commands:</div>
<div>
<br /></div>
<div>
For windows:</div>
<div>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">git config --global credential.helper wincred
</code></pre>
</div>
<div>
<br />
For Mac
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">git config --global credential.helper osckeychain
</code></pre>
</div>
<br />
Once execute above commands, run command that you want to execute, it will prompt for username and password again.<br />
<br />
Hope it helps, let me know in case it does not work.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-53462275090049628982018-03-25T11:03:00.001+05:302018-03-25T11:07:57.200+05:30How to config gulp to run unit test cases using Istanbul with code coverage<div dir="ltr" style="text-align: left;" trbidi="on">
Add below configuration in <b>gulpfile</b>.js for running <b>Istanbul </b>with <b>mocha </b>unit test cases through gulp.<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
const gulp = require('gulp');
const istanbul = require('gulp-istanbul');
const mocha = require('gulp-mocha');
gulp.task('test', () => {
gulp.src(['src/**/*.js'])
.pipe(istanbul())
.pipe(istanbul.hookRequire())
.on('finish', () => {
gulp.src(['test/unit/**/*.spec.js'])
.pipe(mocha())
.pipe(istanbul.writeReports({
dir: './test/unit-test-coverage',
reporters: ['lcov', 'clover', 'text', 'text-summary'],
reportOpts: {
dir: './test/unit-test-coverage',
},
}));
});
});
</code></pre>
<br />
For code coverage, we can use <b>istanbul.writeReports</b> method as shown above.<br />
<br />
Once executing the command <b>gulp test</b>, it will execute all the test cases along with coverage report generated at given location.<br />
<br /></div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1055866655041959795.post-74282550404423301562018-03-25T10:26:00.000+05:302018-03-25T10:42:07.639+05:30Running Jest using Gulp with code coverage<div dir="ltr" style="text-align: left;" trbidi="on">
Jest is a unit test framework that is mainly used for reactjs. Jest is widely used by facebook in their projects.<br />
<br />
Add below configuration in <b>gulpfile</b>.js for running <b>Jest </b>unit test cases through <b>gulp</b><br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
const gulp = require('gulp');
const jestcli = require('jest-cli');
gulp.task('test', () => {
jestcli.runCLI({ config: { rootDir: 'test/unit/' } }, '.', (done) => {
done();
});
});
</code></pre>
<br />
Using command:<b> gulp test</b>, will execute the test cases written under directory <b>'test/unit'</b>. To have code coverage, we can configure it in <b>package.json</b> file as below:<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
"jest": {
"collectCoverage": true,
"coverageDirectory": "./test/unit-test-coverage"
}
</code></pre>
<br />
Add above config in <b>package.json</b> file. for defining custom directory to create the report, mention the directory in coverageDirectory key, otherwise it will generate at root directory.<br />
<br /></div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-1055866655041959795.post-84673941153044938052017-01-27T14:12:00.002+05:302018-03-25T09:47:14.103+05:30How to check if database exists while connecting in HSQLDB<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">In HSQLDB, if while providing connection string if the database does not exists, it creates a new database. However, lets say if we want to restrict HSQLDB to create new Database and only connect to exists one and if not present then throw back an exception, we can specify a connection property <b><i>ifexists=true</i>.</b> This will allow only to connect to an existing database and avoid creating new one. Also, if db does not exists it will throw an exception.</span></div>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> Connection c = DriverManager.getConnection( "jdbc:hsqldb:file:testdb;ifexists=true", "SA", "");
</code></pre>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-2685433491986198952017-01-25T18:16:00.000+05:302017-01-25T18:16:29.583+05:30How to compare two fields value while querying in mongodb<div dir="ltr" style="text-align: left;" trbidi="on">
To compare 2 fields of a document while querying in mongodb, we need to use $where.<br />
<br />
Lets see the example to compare 2 fields of a document:
<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> Employee Collection
{
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"department" : "finance",
"joineddate" : "2010-04-10"
},
{
"_id" : 2,
"name" : {
"first" : "Agrawal",
"last" : "Agrawal"
},
"joineddate" : "2006-07-07"
},
{
"_id" : 3,
"name" : {
"first" : "Dhruv",
"last" : "Agrawal"
},
"department" : "finance",
"joineddate" : "2010-09-07"
}
}
</code></pre>
<br />
Now lets say I need to fetch data which has first and last values are equal.<br />
<br />
The query would be:<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> db.employee.find({ $where : "this.name.last == this.name.first" })
</code></pre>
<br />
The output would be:<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 646.469px;"><code style="word-wrap: normal;">{
"_id" : 2,
"name" : {
"first" : "Agrawal",
"last" : "Agrawal"
}</code></pre>
<br /></div>
Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-1055866655041959795.post-1020065168553963652017-01-18T14:47:00.003+05:302017-01-18T14:47:54.968+05:30How to update specific records of array field in collection using MongoDB<div dir="ltr" style="text-align: left;" trbidi="on">
To update specific records of an array field in MongoDB, we can achieve that by using JavaScript with Mongo query. Below are the two ways to update the arrays. Lets see both ways to update the data.<br />
<br />
Employee Collection:<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"profile":[ {"department" : "finance", "joineddate" : "2010-04-10"},
{"department" : "marketing", "joineddate" : "2008-05-05"},
{"department" : "hr", "joineddate" : "2006-08-05"}
]
},
{
"_id" : 2,
"name" : {
"first" : "Dhruv",
"last" : "Sharma"
},
"profile":[ {"department" : "retail", "joineddate" : "2013-07-10"},
{"department" : "finance", "joineddate" : "2010-05-25"},
{"department" : "hr", "joineddate" : "2007-08-05"}
]
}
</code></pre>
<br />
Objective is to update above array's <i>joineddate</i> field where department is finance.<br />
Option 1: Updating the array using JavaScript:<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> db.employee.find({}).
forEach(function(doc){
doc.profile.forEach(function(d){
if(d.department == "finance")
{
d.joineddate = "2016-12-12"
}
});
db.employee.save(doc);
})
</code></pre>
<br />
Option 2: Updating array using Mongo Query operators update and set:
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> var query = {
profile: {
$elemMatch: {
department: "finance",
joineddate: {$ne: "2016-12-12"}
}
}
};
while (db.employee.find(query).count() > 0) {
db.employee.update(
query,
{ $set: { "profile.$.joineddate": "2016-12-12" } },
{ multi: true }
);
}
</code></pre>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-69445940308036282612017-01-17T17:48:00.001+05:302017-01-17T17:48:07.201+05:30How to update field using data from same document's another field<div dir="ltr" style="text-align: left;" trbidi="on">
We cannot directly use update method to update the field with same document's another field. We need to first iterate the data and then use save method to update the same.<br />
<div>
<br /></div>
<div>
<div>
For example:</div>
<div>
Employee Collection</div>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"full_name" : "AD",
"first" : "Abhi",
"last" : "Dev"
},
"department" : "finance",
"joineddate" : "2010-04-10"
}
</code></pre>
</div>
<br />
Lets say I have above collection document that I need to update. Full name of this document should be updated with First and Last field.<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> db.employee.find().snapshot().forEach(
function (e) {
// update document, using its own properties
e.name.full_name = e.name.first + " " +e.name.last;
// save the updated document
db.employee.save(e);
}
)
</code></pre>
<br />
As you can see here, we are using snapshot query modifier. The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-3400383294479353412017-01-17T12:18:00.000+05:302017-01-17T12:21:54.185+05:30How to connect MongoDB with authentication in JAVA<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
To connect MongoDB through JAVA, we will use MongoClient and to fetch and iterate data we will use MongoCollection and FindIterable classes.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
As of version 3.2, mongoclient.getDB method is deprecated. The deprecation of this method effectively deprecates the DB, DBCollection, and DBCursor classes, among others. That's the reason we will use the new methods and classes like MongoCollection, MongoDatabase and FindIterable correspondingly.</div>
<h4 style="text-align: justify;">
<span style="text-align: left;">Full example of MongoDB connection in JAVA</span></h4>
<div>
<div>
Employee Collection</div>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"department" : "finance",
"joineddate" : "2010-04-10"
},
{
"_id" : 2,
"name" : {
"first" : "Alok",
"last" : "Agrawal"
},
"joineddate" : "2006-07-07"
},
{
"_id" : 3,
"name" : {
"first" : "Dhruv",
"last" : "Sharma"
},
"department" : "finance",
"joineddate" : "2010-09-07"
}
}
</code></pre>
</div>
<div>
JAVA code for Mongo Connection and fetching the data.<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class Test {
public static void main(String[] args) {
String mongoClientURI = "mongodb://username:password@hostname:port/dbname";
MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoClientURI));
MongoDatabase md = mongoClient.getDatabase("dbname");
MongoCollection<Document> mgColl = md.getCollection("employee");
Document assortCCObj = new Document("department", "finance");
assortCCObj.append("joineddate", new Document("$gt", "2010-01-01"));
FindIterable<Document> dt = mgColl.find(assortCCObj);
for (Document document : dt) {
System.out.println(document.toJson());
}
}
}
</code></pre>
</div>
<br />
The above code will connect to mongo and fetch data from employee collection as per the given criteria. </div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-3358567599609513492017-01-16T10:47:00.001+05:302017-01-16T10:51:59.692+05:30MongoDB Topics<div dir="ltr" style="text-align: left;" trbidi="on">
<ul style="text-align: left;">
<li><a href="http://tech-heap.blogspot.in/2017/01/how-to-use-exists-to-check-field-is.html">How to use $EXISTS to check the field is null or not in mongodb</a></li>
</ul>
<ul style="text-align: left;">
<li><span style="background-color: white; color: black; font-family: "arial" , serif; font-size: small; text-decoration: none;"><a href="http://tech-heap.blogspot.in/2017/01/how-to-increase-performance-while.html" style="background-color: white; font-family: arial, serif; text-decoration: none;">How to increase performance while fetching the data from MongoDB</a></span></li>
<li><h4 style="font-family: Arial, serif;">
<span style="background-color: white; color: black; font-size: small;"><a href="http://tech-heap.blogspot.in/2017/01/how-to-use-like-keyword-in-mongodb.html">How to use like keyword in mongodb</a></span></h4>
</li>
<li><h4 style="font-family: Arial, serif;">
<span style="background-color: white; color: black;"><a href="http://tech-heap.blogspot.in/2016/12/execute-mongodb-queries-from-command.html">Execute MongoDB queries from command prompt</a></span></h4>
</li>
<li><h4 style="font-family: Arial, serif;">
<a href="http://tech-heap.blogspot.in/2016/12/example-of-bulk-updates-in-mongodb.html"><span style="background-color: white; color: black; font-size: small;">Example of bulk updates in MongoDB</span></a></h4>
</li>
</ul>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-75015037274199641452017-01-16T10:25:00.003+05:302017-01-16T10:25:51.422+05:30How to use $EXISTS to check the field is null or not in mongodb<div dir="ltr" style="text-align: left;" trbidi="on">
$exists is an element query operator that can be use to check the existense of any field in a document.<br />
<br />
<span class="Apple-tab-span" style="white-space: pre;"> </span><i>Syntax: { field: { $exists: <boolean> } }</boolean></i><br />
<br />
If<i> { $exists: true }</i>, it will matches the documents which contain the field.<br />
<br />
If <i>{ $exists: false }</i>, it will matches the documents which does not contain the field.<br />
<br />
For example:<br />
Employee Collection<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"department" : "finance",
"joineddate" : "2000-04-10"
},
{
"_id" : 2,
"name" : {
"first" : "Alok",
"last" : "Agrawal"
},
"joineddate" : "2006-07-07"
},
{
"_id" : 3,
"name" : {
"first" : "Dhruv",
"last" : "Sharma"
},
"department" : "finance",
"joineddate" : "2010-09-07"
},
{
"_id" : 4,
"name" : {
"first" : "Ravi",
"last" : "Mann"
},
"department" : "information",
"joineddate" : "2008-04-07"
}
}
</code></pre>
<br />
In above collection, document <i>{id : 2}</i> does not have department field. So, lets say if we need to search the documents which does not have department field, the query would be:<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> db.employee.find({department: {$exists : false}})
</code></pre>
Output of Above Query:<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 2,
"name" : {
"first" : "Alok",
"last" : "Agrawal"
},
"joineddate" : "2006-07-07"
}
</code></pre>
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-18637154966529011652017-01-15T11:27:00.000+05:302017-01-15T11:27:20.085+05:30How to increase performance while fetching the data from MongoDB<div dir="ltr" style="text-align: left;" trbidi="on">
MongoDB is a no-sql database, which can contain huge data in collections. Due to non relational /un-structered data, it takes load of time while fetching it from DB.<br />
<br />
We can if query mongo smartly it can fetch the data very fastly. One way to do it is to limit the output data. There would be many cases when the objective of querying the mongo is to just get some specific fields details. For example, I have a collection of employee and I need to search employee first name starts from 'A' and I only need to fetch its first name. now one way is to use below query to fetch the data which will fetch the whole document which mets the criteria:<br />
<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 587.063px;"><code style="word-wrap: normal;"> db.employee.find({"name" : "/^A/"}) </code></pre>
Output:<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 587.063px;"><code style="word-wrap: normal;">{
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"department" : "finance",
"joineddate" : "2000-04-10"
},
{
"_id" : 2,
"name" : {
"first" : "Alok",
"last" : "Agrawal"
},
"department" : "information",
"joineddate" : "2006-07-07"
}</code></pre>
<br />
But if I limit the data outcome and only specify the fields which I want as in this case I only need to see first name, we can use projection and make it possible as:<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 587.063px;"><code style="word-wrap: normal;"> db.employee.find({"name" : "/^A/"},{"name.first":1}) </code></pre>
Output<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 587.063px;"><code style="word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi"
}
},
{
"_id" : 2,
"name" : {
"first" : "Alok
}
}</code></pre>
<br />
As we can see on above output it reduces the data, which will enhance the performance of query.<br />
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-78685513832342584912017-01-15T11:07:00.001+05:302017-01-15T11:11:32.561+05:30How to use like keyword in mongodb<div dir="ltr" style="text-align: left;" trbidi="on">
Like SQL statements we can use LIKE keywords in Mongo as well. We can query mongdb with LIKE search. We can restrict LIKE search as we do in SQL using '%' as<br />
<br />
<pre class="lang-js prettyprint prettyprinted" style="background-color: #eff0f1; border: 0px; color: #393318; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-size: 13px; margin-bottom: 1em; max-height: 600px; overflow: auto; padding: 5px; width: auto; word-wrap: normal;"><code style="border: 0px; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; margin: 0px; padding: 0px; white-space: inherit;"><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">db</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">.</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">employee</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">.</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">find</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">({</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">name</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">:</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;"> </span><span class="str" style="border: 0px; color: #7d2727; margin: 0px; padding: 0px;">/text/</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">})</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;"> </span><span class="com" style="border: 0px; color: #858c93; margin: 0px; padding: 0px;">//like '%text%'</span></code></pre>
<pre class="lang-js prettyprint prettyprinted" style="background-color: #eff0f1; border: 0px; color: #393318; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-size: 13px; margin-bottom: 1em; max-height: 600px; overflow: auto; padding: 5px; width: auto; word-wrap: normal;"><code style="border: 0px; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; margin: 0px; padding: 0px; white-space: inherit;"><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">db</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">.</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">employee</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">.</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">find</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">({</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">name</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">:</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;"> </span><span class="str" style="border: 0px; color: #7d2727; margin: 0px; padding: 0px;">/^txt/</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">})</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;"> </span><span class="com" style="border: 0px; color: #858c93; margin: 0px; padding: 0px;">//like 'text%'</span></code></pre>
<pre class="lang-js prettyprint prettyprinted" style="background-color: #eff0f1; border: 0px; color: #393318; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; font-size: 13px; margin-bottom: 1em; max-height: 600px; overflow: auto; padding: 5px; width: auto; word-wrap: normal;"><code style="border: 0px; font-family: Consolas, Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, sans-serif; margin: 0px; padding: 0px; white-space: inherit;"><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">db</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">.</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">employee</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">.</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">find</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">({</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">name</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">:</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;"> </span><span class="str" style="border: 0px; color: #7d2727; margin: 0px; padding: 0px;">/text$/</span><span class="pun" style="border: 0px; color: #303336; margin: 0px; padding: 0px;">})</span><span class="pln" style="border: 0px; color: #303336; margin: 0px; padding: 0px;"> </span><span class="com" style="border: 0px; color: #858c93; margin: 0px; padding: 0px;">//like 'text%'</span></code></pre>
<b>Examples</b>:<br />
<br />
Employee Collection<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"department" : "finance",
"joineddate" : "2000-04-10"
},
{
"_id" : 2,
"name" : {
"first" : "Alok",
"last" : "Agrawal"
},
"department" : "information",
"joineddate" : "2006-07-07"
},
{
"_id" : 3,
"name" : {
"first" : "Dhruv",
"last" : "Sharma"
},
"department" : "finance",
"joineddate" : "2010-09-07"
}
</code></pre>
<br />
Lets say from above collection I need to search for name which has 'h' in it. So, the query would be:<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> db.employee.find({"name" : "/h/"},{name:1})
</code></pre>
<br />
The above will fetch 2 results from collection as:<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
}
},
{
"_id" : 3,
"name" : {
"first" : "Dhruv",
"last" : "Sharma"
}
}
</code></pre>
<br />
Now, lets say I need to search name that start with 'A', so the query would be:<br />
<pre style="background: rgb(240, 240, 240); border: 1px dashed rgb(204, 204, 204); font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; width: 646.469px;"><code style="word-wrap: normal;"> db.employee.find({"name" : "/^A/"},{name:1})
</code></pre>
<div>
<code style="word-wrap: normal;"><br /></code>
<code style="word-wrap: normal;">Query Output:</code><br />
<code style="word-wrap: normal;"></code>
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
}
},
{
"_id" : 2,
"name" : {
"first" : "Alok",
"last" : "Agrawal"
}
}
</code></pre>
<div>
<code style="word-wrap: normal;"><br /></code>
<code style="word-wrap: normal;">There are many regex we can use similarly to filter the search as per the need.</code></div>
<div>
<code style="word-wrap: normal;"><br /></code></div>
</div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-35344432466999476542016-12-20T17:28:00.002+05:302016-12-20T17:28:31.041+05:30Execute MongoDB queries from command prompt<div dir="ltr" style="text-align: left;" trbidi="on">
Execute MongoDB queries from command prompt<br />
<br />
we can run mongodb queries from command prompt as well. Run command prompt in administrator mode.<br />
<br />
Go to the mongo installation path till bin folder.<br />
<br />
In windows, it should be like:<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> c:\Program Files\Mongo\server\3.2\bin
</code></pre>
<br />
Use below command to execute the mongo query :<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> mongo <hostname>:<portnumber>/<dbname> -u <user> -p <pass> db.employee.find("department" : "finance")
</code></pre>
<br />
The above command will connect to the given DB details and execute the query.<br />
<br />
It will show the data in command prompt itself.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-23461700709315423352016-12-20T17:17:00.000+05:302016-12-20T17:17:44.016+05:30How to print specific data from Collection or document using Javascript in MongoDB<div dir="ltr" style="text-align: left;" trbidi="on">
How to print specific data from Collection or document using Javascript in MongoDB<br />
<br />
Mongo supports javascript queries to handle the data and process as per the need.<br />
<br />
For example,<br />
<br />
Employee collection<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> {
"_id" : 1,
"name" : {
"first" : "Abhi",
"last" : "Dev"
},
"department" : "finance",
"joineddate" : "2000-04-10"
},
{
"_id" : 2,
"name" : {
"first" : "Alok",
"last" : "Agrawal"
},
"department" : "information",
"joineddate" : "2006-07-07"
},
{
"_id" : 3,
"name" : {
"first" : "Dhruv",
"last" : "Sharma"
},
"department" : "finance",
"joineddate" : "2010-09-07"
}
</code></pre>
<br />
Now, lets say I need to print only the name who are in finance department.<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> db.employee.find("department" : "finance").forEach(
function(doc) {
print(doc.name.first + " " + doc.name.last);
);
</code></pre>
<br />
The above query will print all the employee first name and last name whose department is finance.<br />
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-31849150150785721432016-12-16T10:19:00.001+05:302016-12-16T10:19:21.671+05:30Example of bulk updates in MongoDB<div dir="ltr" style="text-align: left;" trbidi="on">
Mongo Allows to have bulk updates using following operation:<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> db.collection.initializeOrderedBulkOp()
</code></pre>
<br />
Initializes and returns a <i>new Bulk()</i> operations builder for a collection.<br />
<br />
The builder constructs an ordered list of write operations that MongoDB executes in bulk.<br />
<br />
Full Example<br />
<br />
In this example we will update name from "ABC One" to "ABC Two" in whole collection<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> //initialize Bulk operation
var bulk = db.test.initializeOrderedBulkOp();
db.test.find({"name": /ABC One/})
.forEach(function(doc){
print (doc.name)
name = doc.name.replace("ABC One", "ABC Two")
bulk.find({"_id" :doc._id}).
updateOne(
{ $set:
{
"name": name
}}
);
print(doc.name)
})
bulk.execute();
</code></pre>
<br />
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-1055866655041959795.post-69316254928814550302016-11-28T11:43:00.001+05:302016-11-28T11:43:20.060+05:30Example of using Models in Backbone JS<div dir="ltr" style="text-align: left;" trbidi="on">
Models are data container where we can also add logics to data like validations, conversions or any specific computation if requires.<br />
<br />
In this post we will understand how can we create our own Model Class and then create methods under it with data variables to contain the data.<br />
<div>
<br /></div>
<div>
Example:</div>
<div>
<br /></div>
<div>
Books Model Class</div>
<div>
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> var bookModel = Backback.Model.extend({});
</code></pre>
</div>
<br />
The above code will create a plain Model class of object bookModel.
Now lets create some variables and set values into that.
<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> bookModel.set({bookName: "BackBone", noOfPages: 80});
</code></pre>
<br />
the above line will create 2 variables under bookModel Model Object.<br />
<br />
To create a function under it, we can do while creating the Model class. For example:<br />
<br />
<pre style="background: #f0f0f0; border: 1px dashed #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> var bookModel = Backback.Model.extend({
publishBookPrice : function (){
alert("the price of this book is 200 INR");
}
});
</code></pre>
<br />
<br /></div>
Unknownnoreply@blogger.com0