Of the four basic database operations (i.e. CRUD), delete operations are those that remove documents from a collection in MongoDB. In Java MongoDB API, you can use collection.remove() to delete document from collection.

If we want to remove the document from the collection ’employees’ which contains the empId “10001” the following mongodb command can be used :

  1. >db.employees.remove( { “empId” : “10001” } )

Use the remove() method to delete documents from a collection. The remove() method has the following syntax:

  1. db.collection.remove( <query>, <justOne> )

Corresponding operation in SQL
The remove() method is analogous to the DELETE statement, and:

the <query> argument corresponds to the WHERE statement, and
the <justOne> argument takes a Boolean and has the same affect as LIMIT 1.

remove() deletes documents from the collection. If you do not specify a query, remove() removes all documents from a collection, but does not remove the indexes.

If we want to remove all data from the collection ’employees’ the following mongodb command can be used :

  1. >db.employees.remove( { } )

For testing the Remove function first we insert 10 documents to employees collection

  1. for (int i=1001; i <= 10010; i++) {
  2.  collection.insert(new BasicDBObject().append(“empId”, i));
  3. }

DBCollection.remove()- 1. Get first document and delete it. In this case, empId = 10001 is deleted.

  1. DBObject doc = collection.findOne(); //get first document
  2. collection.remove(doc);

2. Puts query data in a BasicDBObject object. In this case, empId = 10002 is deleted.

  1. BasicDBObject document = new BasicDBObject();
  2. document.put(“empId”10002);
  3. collection.remove(document);

Query like this only delete empId= 3.

  1. BasicDBObject document = new BasicDBObject();
  2.  document.put(“empId”10002);
  3.  document.put(“empId”10003); //override above value 10002
  4.  collection.remove(document);

Nice try, but query like this will not work, it will delete NOTHING.

  1. BasicDBObject document = new BasicDBObject();
  2.  List<Integer> list = new ArrayList<Integer>();
  3.  list.add(10007);
  4.  list.add(10008);
  5.  document.put(“empId”, list);
  6.  collection.remove(document);

3. Use BasicDBObject directly. In this case, empId = 10002 is deleted.

  1. collection.remove(new BasicDBObject().append(“empId”10002));

4. Puts a “greater than” operator in a BasicDBObject object. In this case, empId = 10003 is deleted.

  1. BasicDBObject query = new BasicDBObject();
  2. query.put(“empId”new BasicDBObject(“$gt”10002));
  3. collection.remove(query);

5. Puts a “in” operator in a BasicDBObject object, construct the query in ArrayList. In this case, empId = 10004 and empId = 10005 are deleted.

  1. BasicDBObject query = new BasicDBObject();
  2. List<Integer> list = new ArrayList<Integer>();
  3. list.add(10004);
  4. list.add(10005);
  5. query.put(“number”new BasicDBObject(“$in”, list));
  6. collection.remove(query);

6. Use cursor to delete all available document.

  1. DBCursor cursor = collection.find();
  2. while (cursor.hasNext()) {
  3.  collection.remove(cursor.next());
  4. }

7. Pass an empty BasicDBObject, and cause it delete all available document.

  1. collection.remove(new BasicDBObject());

More Conditional Operators-
$all-
$all selects the documents where the field holds an array and contains all elements (e.g. <value>, <value1>, etc.) in the array. Consider the following example:

  1. db.inventory.find( { tags: { $all: [ “appliances”“school”“book” ] } } )

$lt- 
Syntax: {field: {$lt: value} } $lt selects the documents where the value of the field is less than (i.e. <) the specified value. Consider the following example:

  1. db.inventory.find( { qty: { $lt: 20 } } )

This query will select all documents in the inventory collection where the qty field value is less than 20.

$gt-
Syntax: {field: {$gt: value} }
$gt selects those documents where the value of the field is greater than (i.e. >) the specified value.

Consider the following example:

  1. db.inventory.find( { qty: { $gt: 20 } } )

This query will select all documents in the inventory collection where the qty field value is greater than 20.

Now lets see the full example on the following java file and its output.

  1. package com.dineshonjava.mongo.test;
  2. import java.net.UnknownHostException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import com.mongodb.BasicDBObject;
  6. import com.mongodb.DB;
  7. import com.mongodb.DBCollection;
  8. import com.mongodb.DBCursor;
  9. import com.mongodb.DBObject;
  10. import com.mongodb.Mongo;
  11. import com.mongodb.MongoException;
  12. /**
  13.  * @author Dinesh Rajput
  14.  *
  15.  */
  16. public class DeleteDocumentDemo {
  17.  /**
  18.   * @param args
  19.   */
  20.  public static void main(String[] args) {
  21.  try {
  22.   // connect to mongoDB, IP and port number
  23.   Mongo mongo = new Mongo(“localhost”27017);
  24.   // get database from MongoDB,
  25.   // if database doesn’t exists, mongoDB will create it automatically
  26.   DB db = mongo.getDB(“dineshonjavaDB”);
  27.   // get a single collection
  28.   DBCollection collection = db.getCollection(“employee”);
  29.   //insert empId 10001 to 10010 for testing
  30.   for (int i=10001; i <= 10010; i++) {
  31.   collection.insert(new BasicDBObject().append(“empId”, i));
  32.   }
  33.   //remove empId = 10001
  34.   DBObject doc = collection.findOne(); //get first document
  35.   collection.remove(doc);
  36.   //remove empId = 10002
  37.   BasicDBObject document = new BasicDBObject();
  38.   document.put(“empId”10002);
  39.   collection.remove(document);
  40.   //remove empId = 10003
  41.   collection.remove(new BasicDBObject().append(“empId”10003));
  42.   //remove empId > 10009 , means delete empId = 10010
  43.   BasicDBObject query = new BasicDBObject();
  44.   query.put(“empId”new BasicDBObject(“$gt”10009));
  45.   collection.remove(query);
  46.   //remove empId = 10004 and 10005
  47.   BasicDBObject query2 = new BasicDBObject();
  48.   List<Integer> list = new ArrayList<Integer>();
  49.   list.add(10004);
  50.   list.add(10005);
  51.   query2.put(“empId”new BasicDBObject(“$in”, list));
  52.   collection.remove(query2);
  53.   //remove all documents
  54.   //DBCursor cursor = collection.find();
  55.   //while (cursor.hasNext()) {
  56.   // collection.remove(cursor.next());
  57.   //}
  58.   //remove all documents , no query means delete all
  59.   //collection.remove(new BasicDBObject());
  60.   //print out the document
  61.   DBCursor cursor = collection.find();
  62.             while(cursor.hasNext()) {
  63.                  System.out.println(cursor.next());
  64.             }
  65.             System.out.println(“Done”);
  66.   } catch (UnknownHostException e) {
  67.    e.printStackTrace();
  68.   } catch (MongoException e) {
  69.    e.printStackTrace();
  70.   }
  71.  }
  72. }

If everything is fine then run as a java application and you will get the following output on the console.

output:
{ “_id” : { “$oid” : “51054d998217798d9fc43545”} , “empId” : 10006}
{ “_id” : { “$oid” : “51054d998217798d9fc43546”} , “empId” : 10007}
{ “_id” : { “$oid” : “51054d998217798d9fc43547”} , “empId” : 10008}
{ “_id” : { “$oid” : “51054d998217798d9fc43548”} , “empId” : 10009}
Done

 

In this tutorail we are going to discuss how to update data into a collection. Update can be done with update(). The update() takes four arguments – criteria, objectnew,upsert and multi.
criteria – Query which specify the record to update;
objectnew– Specify the updated information or it can be used by $ operator (i.e. $inc…).
upsert – An upsert do update the record if match the criteria and insert record if not match.
multi – This argument asks to updates all matching rows or just the first one(which is default).
Our database name is ‘dineshonjavaDB‘ and our collection name is ‘employee‘. Here, inserting two more records.

The update() method is the primary method used to modify documents in a MongoDB collection. By default, the update()method updates a single document, but by using the multi option, update() can update all documents that match the query criteria in the collection. The update() method can either replace the existing document with the new document or update specific fields in the existing document.
The update() has the following syntax:

db.collection.update( <query>, <update>, <options> )
Corresponding operation in SQL

The update() method corresponds to the UPDATE operation in SQL, and:

  • the <query> argument corresponds to the WHERE statement, and
  • the <update> corresponds to the SET ... statement.
The default behavior of the update() method updates a single document and would correspond to the SQL UPDATE statement with the LIMIT 1. With the multi option, update() method would correspond to the SQL UPDATE statement without theLIMIT clause.

Click here to know more about the Update command and its options.

In Java MongoDB API, you can use collection.update() to update an existing document. Here is some common use cases :

1. A normal way to update an existing document.
Find empId = 10006, and update it with a new document.

  1. BasicDBObject newDocument = new BasicDBObject();
  2. newDocument.put(“empId”10006);
  3. newDocument.put(“empName”“Dinesh Rajput”);
  4. newDocument.put(“salary”70000);
  5. collection.update(new BasicDBObject().append(“empId”10006), newDocument);

2. This example show the use of “$inc” modifier to increase a particular value.
Find empId = 10006, update the “salary” value by increasing its value from 70000 to 90000, (70000 + 20000) = 90000.

  1. BasicDBObject newDocument = new BasicDBObject().append(“$inc”,
  2. new BasicDBObject().append(“salary”20000));
  3. collection.update(new BasicDBObject().append(“empId”10006), newDocument);

3. This example show the use of “$set” modifier to update a particular value.
Find empId = 10006, update the “salary” from 70000 to 90000.

  1. BasicDBObject newDocument = new BasicDBObject().append(“$set”,
  2.  new BasicDBObject().append(“salary”90000));
  3. collection.update(new BasicDBObject().append(“empId”10006), newDocument);


4. This example show the use of “multi” parameter to update a set of matched documents.
Find empAge= 26, update all the matched documents, “salary” value to 60000.

  1. //find empAge= 26 , update all matched documents , “salary” value to 60000
  2. BasicDBObject updateQuery = new BasicDBObject().append(“$set”,
  3.  new BasicDBObject().append(“salary”“60000”));
  4. //both methods are doing the same thing.
  5. //collection.updateMulti(new BasicDBObject().append(“empAge”, “26”), updateQuery);
  6. collection.update(new BasicDBObject().append(“empAge”“26”), updateQuery, falsetrue);

See the full example and its output.

  1. package com.dineshonjava.mongo.test;
  2. import java.net.UnknownHostException;
  3. import com.mongodb.BasicDBObject;
  4. import com.mongodb.DB;
  5. import com.mongodb.DBCollection;
  6. import com.mongodb.DBCursor;
  7. import com.mongodb.Mongo;
  8. import com.mongodb.MongoException;
  9. /**
  10.  * @author Dinesh Rajput
  11.  *
  12.  */
  13. public class UpdateDocumentDemo {
  14.  public static void printAllDocuments(DBCollection collection){
  15.   DBCursor cursor = collection.find();
  16.   while (cursor.hasNext()) {
  17.    System.out.println(cursor.next());
  18.   }
  19.  }
  20.  public static void removeAllDocuments(DBCollection collection){
  21.   collection.remove(new BasicDBObject());
  22.  }
  23.  public static void insertDummyDocuments(DBCollection collection){
  24.   BasicDBObject document = new BasicDBObject();
  25.   document.put(“empId”“10006”);
  26.   document.put(“empName”“Dinesh”);
  27.   document.put(“salary”70000);
  28.   BasicDBObject document2 = new BasicDBObject();
  29.   document2.put(“empId”“10007”);
  30.   document2.put(“empName”“Sweety”);
  31.   document2.put(“salary”70000);
  32.   BasicDBObject document3 = new BasicDBObject();
  33.   document3.put(“empId”“10008”);
  34.   document3.put(“empName”“Dinesh”);
  35.   document3.put(“salary”60000);
  36.   collection.insert(document);
  37.   collection.insert(document2);
  38.   collection.insert(document3);
  39.  }
  40.  public static void main(String[] args) {
  41.  try {
  42.   Mongo mongo = new Mongo(“localhost”27017);
  43.   DB db = mongo.getDB(“dineshonjavaDB”);
  44.   // get a single collection
  45.   DBCollection collection = db.getCollection(“employee”);
  46.   System.out.println(“Testing 1…”);
  47.   insertDummyDocuments(collection);
  48.   //find empId = 10006, and update it with new document
  49.   BasicDBObject newDocument = new BasicDBObject();
  50.   newDocument.put(“empId”“10006”);
  51.   newDocument.put(“empName”“Dinesh Rajput”);
  52.   newDocument.put(“salary”80000);
  53.   collection.update(new BasicDBObject().append(“empId”“10006”), newDocument);
  54.   printAllDocuments(collection);
  55.   removeAllDocuments(collection);
  56.   System.out.println(“Testing 2…”);
  57.   insertDummyDocuments(collection);
  58.   //find empId = 10006 and increase its “salary” value by 90000
  59.   BasicDBObject newDocument2 = new BasicDBObject().append(“$inc”,
  60.     new BasicDBObject().append(“salary”20000));
  61.   collection.update(new BasicDBObject().append(“empId”“10006”), newDocument2);
  62.   printAllDocuments(collection);
  63.   removeAllDocuments(collection);
  64.   System.out.println(“Testing 3…”);
  65.   insertDummyDocuments(collection);
  66.   //find empId = 10006 and update salary to from 70000 to 90000
  67.   BasicDBObject newDocument3 = new BasicDBObject().append(“$set”,
  68.     new BasicDBObject().append(“salary”90000));
  69.   collection.update(new BasicDBObject().append(“empId”“10006”), newDocument3);
  70.   printAllDocuments(collection);
  71.   removeAllDocuments(collection);
  72.   System.out.println(“Testing 4…”);
  73.   insertDummyDocuments(collection);
  74.   //find empName = Dinesh , update all matched documents , salary value to 80000
  75.   BasicDBObject updateQuery = new BasicDBObject().append(“$set”,
  76.     new BasicDBObject().append(“salary”80000));
  77.   //both method are same
  78.   //collection.updateMulti(new BasicDBObject().append(“empName”, “Dinesh”), updateQuery);
  79.   collection.update(new BasicDBObject().append(“empName”“Dinesh”), updateQuery, falsetrue);
  80.   printAllDocuments(collection);
  81.   removeAllDocuments(collection);
  82.   System.out.println(“Done”);
  83.   } catch (UnknownHostException e) {
  84.    e.printStackTrace();
  85.   } catch (MongoException e) {
  86.    e.printStackTrace();
  87.   }
  88.  }
  89. }

if every thing fine then run as java application and see the follwing output on the console.

output:
Testing 1…
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428bf”} , “empId” : “10007” , “empName” : “Sweety” , “salary” : 70000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c0”} , “empId” : “10008” , “empName” : “Dinesh” , “salary” : 60000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428be”} , “empId” : “10006” , “empName” : “Dinesh Rajput” , “salary” : 80000}
Testing 2…
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c1”} , “empId” : “10006” , “empName” : “Dinesh” , “salary” : 90000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c2”} , “empId” : “10007” , “empName” : “Sweety” , “salary” : 70000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c3”} , “empId” : “10008” , “empName” : “Dinesh” , “salary” : 60000}
Testing 3…
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c4”} , “empId” : “10006” , “empName” : “Dinesh” , “salary” : 90000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c5”} , “empId” : “10007” , “empName” : “Sweety” , “salary” : 70000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c6”} , “empId” : “10008” , “empName” : “Dinesh” , “salary” : 60000}
Testing 4…
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c7”} , “empId” : “10006” , “empName” : “Dinesh” , “salary” : 80000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c8”} , “empId” : “10007” , “empName” : “Sweety” , “salary” : 70000}
{ “_id” : { “$oid” : “51055d6f8217d9c7d67428c9”} , “empId” : “10008” , “empName” : “Dinesh” , “salary” : 80000}
Done

 

In this tutorial we will discussing about inserting a document to the MongoDB. There are four ways to inserting document JSON format to the MongoDB. Here in this page we are going to discuss how to insert data into a collection. The documents stored in MongoDB are JSON-like. All data stored into the collection are in BSON format.

Switch to a MongoDB database-
Here, our database is “dineshonjavaDB”.

> use dineshonjavaDB
switch to db dineshonjavaDB

1. Define a document for MongoDB database-
The following document can be stored in MongoDB.

  1. > document=({“empId” : “10001”,“empName” :“Dinesh Rajput” ,“date_of_join” : “10/04/2010”
  2.  ,“education” :“M.C.A.” , “profession” : “DEVELOPER”,“interest” : “MUSIC”,“community_name”
  3.  :[“MODERN MUSIC”“CLASSICAL MUSIC”,“WESTERN MUSIC”],“community_moder_id” : [“MR. BBB”,”MR.
  4.  JJJ“,”MR MMM“],”community_members” : [500,200,1500],”friends_id” :
  5. [“MMM123”,“NNN123”,“OOO123”],“ban_friends_id” :[“BAN123”,“BAN456”,“BAN789”]});

2. DBCollection.insert()- Insert a document into a collection-
To save the above document into the collection “employees” under “dineshonjavaDB” database the following command can be used –

  1. > db.employees.insert(document)

There are 4 Ways to insert data into MongoDB using Java API.

1. BasicDBObject example

  1. BasicDBObject document = new BasicDBObject();
  2. document.put(“database”“dineshonjavaDB”);
  3. document.put(“table”“employees”);
  4. BasicDBObject documentDetail = new BasicDBObject();
  5. documentDetail.put(“empId”“10001”);
  6. documentDetail.put(“empName”“Dinesh”);
  7. documentDetail.put(“salary”“70000”);
  8. document.put(“detail”, documentDetail);
  9. collection.insert(document);

2. BasicDBObjectBuilder example

  1. BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
  2.   .add(“database”“dineshonjavaDB”)
  3.   .add(“table”“employees”);
  4.  BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
  5.  .add(“empId”“10001”)
  6.  .add(“empName”“Dinesh”)
  7.  .add(“salary”“70000”);
  8.  documentBuilder.add(“detail”, documentBuilderDetail.get());
  9.  collection.insert(documentBuilder.get());
  • Create a new BasicDBObject and invoke its put() method to set the document attributes.
  • Create a BasicDBObjectBuilder instance (that follows the builder design pattern) by invoking the staticBasicDBObjectBuilder.start() method, calling the add() method to add attributes to the document, and then invoking get() to retrieve the resultant DBObject, which is the approach I took when building the employees document

3. Map example

  1. Map<String, Object> documentMap = new HashMap<String, Object>();
  2. documentMap.put(“database”“dineshonjavaDB”);
  3. documentMap.put(“table”“employees”);
  4. Map<String, Object> documentMapDetail = new HashMap<String, Object>();
  5. documentMapDetail.put(“empId”“10001”);
  6. documentMapDetail.put(“empName”“Dinesh”);
  7. documentMapDetail.put(“salary”“70000”);
  8. documentMap.put(“detail”, documentMapDetail);
  9. collection.insert(new BasicDBObject(documentMap));

4. JSON parse example

  1. String json = “{‘database’ : ‘dineshonjavaDB’,’table’ : ’employees’,” +
  2.  “‘detail’ : {’empId’ : 10001, ’empName’ : ‘Dinesh’, ‘salary’ : 70000}}}”;
  3. DBObject dbObject = (DBObject)JSON.parse(json);
  4. collection.insert(dbObject);

Now see the full example of Inserting data into the collection

  1. package com.dineshonjava.mongo.test;
  2. import java.net.UnknownHostException;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import com.mongodb.BasicDBObject;
  6. import com.mongodb.BasicDBObjectBuilder;
  7. import com.mongodb.DB;
  8. import com.mongodb.DBCollection;
  9. import com.mongodb.DBCursor;
  10. import com.mongodb.DBObject;
  11. import com.mongodb.Mongo;
  12. import com.mongodb.MongoException;
  13. import com.mongodb.util.JSON;
  14. /**
  15.  * @author Dinesh Rajput
  16.  *
  17.  */
  18. public class InsertDocumentDemo {
  19.  /**
  20.   * @param args
  21.   */
  22.  public static void main(String[] args) {
  23.  try {
  24.   // connect to mongoDB, IP and port number
  25.   Mongo mongo = new Mongo(“localhost”27017);
  26.   // get database from MongoDB,
  27.   // if database doesn’t exists, mongoDB will create it automatically
  28.   DB db = mongo.getDB(“dineshonjavaDB”);
  29.   // get a single collection
  30.   DBCollection collection = db.getCollection(“employees”);
  31.   // BasicDBObject example
  32.   System.out.println(“BasicDBObject example…”);
  33.   BasicDBObject document = new BasicDBObject();
  34.   document.put(“database”“dineshonjavaDB”);
  35.   document.put(“table”“employees”);
  36.   BasicDBObject documentDetail = new BasicDBObject();
  37.   documentDetail.put(“empId”“10001”);
  38.   documentDetail.put(“empName”“Dinesh”);
  39.   documentDetail.put(“salary”“70000”);
  40.   document.put(“detail”, documentDetail);
  41.   collection.insert(document);
  42.   DBCursor cursorDoc = collection.find();
  43.   while (cursorDoc.hasNext()) {
  44.   System.out.println(cursorDoc.next());
  45.   }
  46.   collection.remove(new BasicDBObject());
  47.   // BasicDBObjectBuilder example
  48.   System.out.println(“BasicDBObjectBuilder example…”);
  49.  BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
  50.    .add(“database”“dineshonjavaDB”)
  51.                         .add(“table”“employees”);
  52. BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
  53.                     .add(“empId”“10001”)
  54.                     .add(“empName”“Dinesh”)
  55.            .add(“salary”“70000”);
  56.  documentBuilder.add(“detail”, documentBuilderDetail.get());
  57.  collection.insert(documentBuilder.get());
  58.  DBCursor cursorDocBuilder = collection.find();
  59.  while (cursorDocBuilder.hasNext()) {
  60.   System.out.println(cursorDocBuilder.next());
  61.  }
  62.  collection.remove(new BasicDBObject());
  63.  // Map example
  64.  System.out.println(“Map example…”);
  65.  Map<String, Object> documentMap = new HashMap<String, Object>();
  66.  documentMap.put(“database”“dineshonjavaDB”);
  67.  documentMap.put(“table”“employees”);
  68.  Map<String, Object> documentMapDetail = new HashMap<String, Object>();
  69.  documentMapDetail.put(“empId”“10001”);
  70.  documentMapDetail.put(“empName”“Dinesh”);
  71.  documentMapDetail.put(“salary”“70000”);
  72.  documentMap.put(“detail”, documentMapDetail);
  73.  collection.insert(new BasicDBObject(documentMap));
  74.  DBCursor cursorDocMap = collection.find();
  75.  while (cursorDocMap.hasNext()) {
  76.   System.out.println(cursorDocMap.next());
  77.  }
  78.  collection.remove(new BasicDBObject());
  79.  // JSON parse example
  80.  System.out.println(“JSON parse example…”);
  81.  String json = “{‘database’ : ‘dineshonjavaDB’,’table’ : ’employees’,” +
  82.  “‘detail’ : {’empId’ : 10001, ’empName’ : ‘Dinesh’, ‘salary’ : ‘70000’}}}”;
  83.  DBObject dbObject = (DBObject)JSON.parse(json);
  84.  collection.insert(dbObject);
  85.  DBCursor cursorDocJSON = collection.find();
  86.  while (cursorDocJSON.hasNext()) {
  87.   System.out.println(cursorDocJSON.next());
  88.  }
  89.  //collection.remove(new BasicDBObject());
  90.  System.out.println(“Done”);
  91. catch (UnknownHostException e) {
  92.    e.printStackTrace();
  93. catch (MongoException e) {
  94.    e.printStackTrace();
  95. }
  96. }
  97. }

If every thing is fine then run as Java Application then we will get the following output on the console.

output:
BasicDBObject example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84ae”} , “database” : “dineshonjavaDB” , “table” : “employees” , “detail” : { “empId” : “10001” , “empName” : “Dinesh” , “salary” : “70000”}}
BasicDBObjectBuilder example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84af”} , “database” : “dineshonjavaDB” , “table” : “employees” , “detail” : { “empId” : “10001” , “empName” : “Dinesh” , “salary” : “70000”}}
Map example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84b0”} , “detail” : { “empName” : “Dinesh” , “empId” : “10001” , “salary” : “70000”} , “table” : “employees” , “database” : “dineshonjavaDB”}
JSON parse example…
{ “_id” : { “$oid” : “5104d7cc37de7e0a362e84b1”} , “database” : “dineshonjavaDB” , “table” : “employees” , “detail” : { “empId” : 10001 , “empName” : “Dinesh” , “salary” : “70000”}}
Done
In this tutorial one Of the four basic database operations (i.e. CRUD), read operation are those that retrieve records or documents from a collection in MongoDB. For general information about read operations and the factors that affect their performance, see Read Operations; for documentation of the other CRUD operations.

You can retrieve documents from MongoDB using either of the following methods:

  • find
  • findOne

FIND

The find() method is the primary method to select documents from a collection. The find() method returns a cursor that contains a number of documents. Most drivers provide application developers with a native iterable interface for handling cursors and accessing documents. The find() method has the following syntax:

db.collection.find( <query>, <projection> )

Corresponding Operation in SQL

The find() method is analogous to the SELECT statement, while:

  • the <query> argument corresponds to the WHERE statement, and
  • the <projection> argument corresponds to the list of fields to select from the result set.

FIND ONE

The findOne() method selects and returns a single document from a collection and returns that document. findOne() does notreturn a cursor.

The findOne() method has the following syntax:

db.collection.findOne( <query>, <projection> )

Except for the return value, findOne() method is quite similar to the find() method; in fact, internally, the findOne() method is the find() method with a limit of 1.

Cursor

The find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable, then the cursor is automatically iterated up to 20 times  to print up to the first 20 documents that match the query, as in the following example:

db.bios.find( { _id: 1 } );
 Click here to know more about the Read Data and its options.

In Java MongoDB API, you can use collection.find() to get / query document from collection. Here is few common use cases :

For this example we have insert some document into the mongoDB “dineshonjavaDB
as follows inserting 10 documents to the “employee” collection on mongoDB.

  1. for (int i=10001; i <= 10010; i++) {
  2.  collection.insert(new BasicDBObject().append(“empId”, i));
  3. }

1. Fetch first record.

  1. DBObject doc = collection.findOne(); //get first document
  2. System.out.println(dbObject);

2. Get the set of document.

  1. DBCursor cursor = collection.find();
  2. while(cursor.hasNext()) {
  3.     System.out.println(cursor.next());
  4. }

3. fetch documents where empId = 8.

  1. BasicDBObject query = new BasicDBObject();
  2. query.put(“empId”10008);
  3. DBCursor cursor = collection.find(query);
  4. while(cursor.hasNext()) {
  5.     System.out.println(cursor.next());
  6. }

4. fetch documents where number = 10009 and 10010, use “$in” operator.

  1. BasicDBObject query = new BasicDBObject();
  2. List<Integer> list = new ArrayList<Integer>();
  3. list.add(10009);
  4. list.add(10010);
  5. query.put(“empId”new BasicDBObject(“$in”, list));
  6. DBCursor cursor = collection.find(query);
  7. while(cursor.hasNext()) {
  8.    System.out.println(cursor.next());
  9. }

5. fetch documents where empId > 10003, use “$gt” operator.

  1. BasicDBObject query = new BasicDBObject();
  2. query.put(“empId”new BasicDBObject(“$gt”10003));
  3. DBCursor cursor = collection.find(query);
  4. while(cursor.hasNext()) {
  5.  System.out.println(cursor.next());
  6. }

6. fetch documents where 10002 < number < 10005, combine two operators, “$gt” and “$lt”.

  1. BasicDBObject query = new BasicDBObject();
  2. query.put(“empId”new BasicDBObject(“$gt”10002).append(“$lt”10005));
  3. DBCursor cursor = collection.find(query);
  4. while(cursor.hasNext()) {
  5.  System.out.println(cursor.next());
  6. }

7. fetch documents where number != 10001, use “$ne” operator.

  1. BasicDBObject query = new BasicDBObject();
  2. query.put(“empId”new BasicDBObject(“$ne”10001));
  3. DBCursor cursor = collection.find(query);
  4. while(cursor.hasNext()) {
  5.   System.out.println(cursor.next());
  6. }

Now lets see the full example and run this ..

  1. package com.dineshonjava.mongo.test;
  2. import java.net.UnknownHostException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import com.mongodb.BasicDBObject;
  6. import com.mongodb.DB;
  7. import com.mongodb.DBCollection;
  8. import com.mongodb.DBCursor;
  9. import com.mongodb.DBObject;
  10. import com.mongodb.Mongo;
  11. import com.mongodb.MongoException;
  12. /**
  13.  * @author Dinesh Rajput
  14.  *
  15.  */
  16. public class ReadDocumentDemo {
  17.  public static void main(String[] args) {
  18.  try {
  19.   Mongo mongo = new Mongo(“localhost”27017);
  20.   DB db = mongo.getDB(“dineshonjavaDB”);
  21.   // get a single collection
  22.   DBCollection collection = db.getCollection(“employeesCollection”);
  23.   // insert empId 10001 to 10010 for testing
  24.   for (int i = 10001; i <= 10010; i++) {
  25.    collection.insert(new BasicDBObject().append(“empId”, i));
  26.   }
  27.   // get first document
  28.   DBObject dbObject = collection.findOne();
  29.   System.out.println(dbObject);
  30.   System.out.println(“*****************First Test*****************”);
  31.   // get all available documents
  32.   DBCursor cursor = collection.find();
  33.   while (cursor.hasNext()) {
  34.    System.out.println(cursor.next());
  35.   }
  36.   System.out.println(“*****************Second Test*****************”);
  37.   // get document, where empId = 10003
  38.   BasicDBObject query = new BasicDBObject();
  39.   query.put(“empId”10003);
  40.   DBCursor cursor2 = collection.find(query);
  41.   while (cursor2.hasNext()) {
  42.    System.out.println(cursor2.next());
  43.   }
  44.   System.out.println(“*****************Third Test*****************”);
  45.   // get document, where empId = 10002 and empId = 10004
  46.   BasicDBObject query2 = new BasicDBObject();
  47.   List<Integer> list = new ArrayList<Integer>();
  48.   list.add(10002);
  49.   list.add(10004);
  50.   query2.put(“empId”new BasicDBObject(“$in”, list));
  51.   DBCursor cursor3 = collection.find(query2);
  52.   while (cursor3.hasNext()) {
  53.    System.out.println(cursor3.next());
  54.   }
  55.   System.out.println(“*****************Fourth Test*****************”);
  56.   // get document, where empId > 10006
  57.   BasicDBObject query3 = new BasicDBObject();
  58.   query3.put(“empId”new BasicDBObject(“$gt”10006));
  59.   DBCursor cursor4 = collection.find(query3);
  60.   while (cursor4.hasNext()) {
  61.    System.out.println(cursor4.next());
  62.   }
  63.   System.out.println(“*****************Fifth Test*****************”);
  64.   // get document, where 10005 < empId < 10007
  65.   BasicDBObject query4 = new BasicDBObject();
  66.   query4.put(“empId”new BasicDBObject(“$gt”10005).append(“$lt”10007));
  67.   DBCursor cursor5 = collection.find(query4);
  68.   while (cursor5.hasNext()) {
  69.    System.out.println(cursor5.next());
  70.   }
  71.   System.out.println(“*****************Sixth Test*****************”);
  72.   // get document, where empId != 10008
  73.   BasicDBObject query5 = new BasicDBObject();
  74.   query5.put(“empId”new BasicDBObject(“$ne”10008));
  75.   DBCursor cursor6 = collection.find(query5);
  76.   while (cursor6.hasNext()) {
  77.    System.out.println(cursor6.next());
  78.   }
  79.   System.out.println(“Done”);
  80.   } catch (UnknownHostException e) {
  81.    e.printStackTrace();
  82.   } catch (MongoException e) {
  83.    e.printStackTrace();
  84.   }
  85.  }
  86. }

If every thing is fine then run as Java Application we will get the following output on the console.

output: 
{ “_id” : { “$oid” : “5106c015c781b5829079a5da”} , “empId” : 10001}
*****************First Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5da”} , “empId” : 10001}
{ “_id” : { “$oid” : “5106c015c781b5829079a5db”} , “empId” : 10002}
{ “_id” : { “$oid” : “5106c015c781b5829079a5dc”} , “empId” : 10003}
{ “_id” : { “$oid” : “5106c015c781b5829079a5dd”} , “empId” : 10004}
{ “_id” : { “$oid” : “5106c015c781b5829079a5de”} , “empId” : 10005}
{ “_id” : { “$oid” : “5106c015c781b5829079a5df”} , “empId” : 10006}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e0”} , “empId” : 10007}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e1”} , “empId” : 10008}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e2”} , “empId” : 10009}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e3”} , “empId” : 10010}
*****************Second Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5dc”} , “empId” : 10003}
*****************Third Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5db”} , “empId” : 10002}
{ “_id” : { “$oid” : “5106c015c781b5829079a5dd”} , “empId” : 10004}
*****************Fourth Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5e0”} , “empId” : 10007}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e1”} , “empId” : 10008}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e2”} , “empId” : 10009}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e3”} , “empId” : 10010}
*****************Fifth Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5df”} , “empId” : 10006}
*****************Sixth Test*****************
{ “_id” : { “$oid” : “5106c015c781b5829079a5da”} , “empId” : 10001}
{ “_id” : { “$oid” : “5106c015c781b5829079a5db”} , “empId” : 10002}
{ “_id” : { “$oid” : “5106c015c781b5829079a5dc”} , “empId” : 10003}
{ “_id” : { “$oid” : “5106c015c781b5829079a5dd”} , “empId” : 10004}
{ “_id” : { “$oid” : “5106c015c781b5829079a5de”} , “empId” : 10005}
{ “_id” : { “$oid” : “5106c015c781b5829079a5df”} , “empId” : 10006}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e0”} , “empId” : 10007}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e2”} , “empId” : 10009}
{ “_id” : { “$oid” : “5106c015c781b5829079a5e3”} , “empId” : 10010}
Done

 

Authentication to MongoDB with Java

Posted: August 5, 2014 in MongoDB

MongoDB can be run in a secure mode where access to databases is controlled through name and password authentication. When run in this mode, any client application must provide a name and password before doing any operations. In the Java driver, you simply do the following with a MongoClient instance:

  1. MongoClient mongoClient = new MongoClient();
  2. DB db = mongoClient.getDB(“test”);
  3. boolean auth = db.authenticate(myUserName, myPassword);

If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.

Most users run MongoDB without authentication in a trusted environment.In this tutorial, we show you how to start MongoDB in secure mode (authentication access is require), and uses Java driver to connect MongoDB with provided username and password.

1. Start MongoDB in Secure Mode
Create an user “dineshonjava” in MongoDB database “dineshonjavaDB”.

  1. > use dineshonjavaDB
  2. > db.addUser(“dineshonjava”,“password”)

To start mongoDB in secure mode, just provide the “–auth” argument

  1. > mongod –auth

2. Now, the MongoDB is started in secure /authentication mode (authenticate with username and password is require).
if you try to access the auth db then we will get following.

  1. > db.auth(“dineshonjava”,“password”)
  2. 1
  3. > db.auth(“dineshonjava”,“password1”)
  4. Error: { errmsg: “auth fails”, ok: 0.0 }
  5. 0
  6. >

3. Java connect MongoDB
In Java, you can use “db.authenticate” to handle the MongoDB authentication.

  1. DB db = mongo.getDB(“dineshonjavaDB”);
  2. boolean auth = db.authenticate(“dineshonjava”“password”.toCharArray());

If username and password is valid, “auth” will be true, else it will be false and return the following error pattern

  1. com.mongodb.MongoException: unauthorized db:dineshonjavaDB lock type:-1 client:192.168.1.3
  2.  at com.mongodb.MongoException.parse(MongoException.java:82)
  3.  at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:302)
  4.  at com.mongodb.DBCursor._check(DBCursor.java:354)
  5.  at com.mongodb.DBCursor._hasNext(DBCursor.java:484)
  6.  at com.mongodb.DBCursor.hasNext(DBCursor.java:509)
  7.  at com.dineshonjava.mongo.test.MongoAuthDemo.main(MongoAuthDemo.java:24)

See the full example as follows.

  1. package com.dineshonjava.mongo.test;
  2. import java.net.UnknownHostException;
  3. import com.mongodb.DB;
  4. import com.mongodb.DBCollection;
  5. import com.mongodb.Mongo;
  6. import com.mongodb.MongoException;
  7. /**
  8.  * @author Dinesh Rajput
  9.  *
  10.  */
  11. public class MongoAuthDemo {
  12.  public static void main(String[] args) {
  13.  try {
  14.   Mongo mongo = new Mongo(“localhost”27017);
  15.   DB db = mongo.getDB(“dineshonjavaDB”);
  16.   boolean auth = db.authenticate(“dineshonjava”“password”.toCharArray());
  17.   DBCollection collection = db.getCollection(“empCollection”);
  18.   if(auth){
  19.    System.out.println(“TRUE”);
  20.   }else{
  21.    System.out.println(“FALSE”);
  22.   }
  23.   System.out.println(“Done”);
  24.   } catch (UnknownHostException e) {
  25.    e.printStackTrace();
  26.   } catch (MongoException e) {
  27.    e.printStackTrace();
  28.   }
  29.  }
  30. }

If everything is fine then we will get the following output-

output-
TRUE
Done

 

Hi in this tutorial we will discuss about the creating databases and collections in the MongoDB. Actually there is no command to create database in  the MongoDB, it created automatically when will try to insert data in to the database name.

MongoDB didn’t provides any command to create “database“. Actually, you don’t need to create it manually, because, MangoDBwill create it on the fly, during the first time you save the value into the defined collection (or table in SQL), and database.

For developer from SQL background, we need to create a database, table and insert values into table manually. In MongoDB, you don’t need to mention what you want to create, when first time you save the value into the defined collection (table), under selected database, MangoDB will create the value, collection and database automatically.

Note :
MongoDB contains “db.createCollection()” to create collection manually, but Not database.
Databases:
A number of databases can be run on a single MongoDB server. Default database of MongoDB is “db“, which is stored within data folder.
MongoDB can create databases on the fly. It is not required to create a database before you start working with it.
show dbs” command provides you with a list of all the databases.
1. Show all database-
Open the Command prompt and go to the c:/cd mongodb/bin and press enter and run the c:/mongodb/bin> mongod and otherc:/mongodb/bin> mongo

  1. > show dbs
  2. dineshonjavaDB  0.203125GB
  3. local   (empty)
  4. mydb    0.203125GB
  5. >

Here show all databases list.
dineshonjavaDB
local
mydb

Run ‘db’ command to refer to the current database object or connection.

  1. > db
  2. dineshonjavaDB
  3. >


To connect to a particular database, run use command.

  1. > use dineshonjavaDB
  2. switched to db dineshonjavaDB

Database names can be almost any character in the ASCII range. But they can’t contain an empty string, a dot (i.e. “.”) or ” “. Since it is reserved, “system” can’t be used as a database name. A database name can contain “$”.

Documents-
document is the unit of storing data in a MongoDB database. document use JSON (JavaScript Object Notation, is a lightweight, thoroughly explorable format used to interchange data between various applications) style for storing data.
A simple example of a JSON document is as follows :
{ empName: “Dinesh” }
Often, the term “object” is used to refer a document.

Documents are analogous to the records of a RDBMS. Insert, update and delete operations can be performed on a collection. The following table will help you to understand the concept more easily :

RDBMS MongoDB
Table Collection
Column Key
Value Value
Records / Rows Document / Object

Collections-
A collection may store number of documents. A collection is analogous to a table of a RDBMS.

A collection may store documents those who are not same in structure. This is possible because MongoDB is a Schema-free database. In a relational database like MySQL, a schema defines the organization / structure of data in database. MongoDB does not require such a set of formula defining structure of data. So, it is quite possible to store documents of varying structures in a collection. Practically, you don’t need to define a column and it’s datatype unlike in RDBMS, while working with MongoDB.

In the following code, it is shown that two MongoDB documents, belongs to same collection, storing data of different structures.

{“empName” : “Dinesh”} {“salary” : 70000}

A collection is created, when the first document is inserted.

Valid collection names-
Collection names must begin with letters or an underscore.

A Collection name may contain numbers.

You can’t use “$” character within the name of a collection. “$” is reserved.

A Collection name must not exceed 128 characters. It will be nice if you keep it within 80/90 characters.

Using a “.” (dot) notation, collections can be organized in named groups. For example, tutorials.php and tutorials.javascript both belong to tutorials. This mechanism is called as collection namespace which is for user primarily. Databases don’t have much to do with it.

Following is how to use it programmatically :

db.employees.dav.findOne()

capped collections-
Imagine that you want to log the activities happening with application. you want to store data in the same order it is inserted. MongoDB offers Capped collections for doing so.

Capped collections are collections which can store data in the same order it is inserted.

It is very fixed size, high-performance and “auto-FIFO age-Out”. That is, when the allotted space is fully utilized, newly added objects (documents) will replace the older ones in the same order it is inserted.

Since data is stored in the natural order, that is the order it is inserted, while retrieving data, no ordering is required, unless you want to reverse the order.

New objects can be inserted into a capped collection.

Existing objects can be updated.

But you can’t remove an individual object from the capped collection. Using drop command, you have to remove all the documents. After drop, you have to recreate the capped collection.

Install MongoDB on Windows

Posted: August 5, 2014 in MongoDB

In this tutorial, we will show you how to install MongoDB on Windows. There are following steps to Install MongoDB on windows OS.

Step: 1. Download MongoDB-
Download the MongoDB from the official MongoDB website. Pre built binary packages of MongoDb are available for both 32 bit and 64 bit. You can download it, and install.

Step: 2. Unzip MongoDB folder and creating directory
Unzip it to your prefer location, for example : C:\mongodb\

Step: 3. Review MongoDB folder-
In MongoDB v2.2.2, it contains only 13 executable files (exe) in the bin folder.

Step: 4. Set Up The Environment
MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is C:\data\db. Create this folder using the Command Prompt. Issue the following command sequence:

md data
md data\db
Note

You may specify an alternate path for \data\db with the dbpath setting for mongod.exe, as in the following example:

C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data

If your path includes spaces, enclose the entire path in double quotations, for example:

C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"

Step: 5. Run the MongoDb server from command prompt
To run MongoDb server from command prompt, you have to execute mongod.exe file from bin folder of mongodb folder.

Step: 6. In additional, MongoDB come with a web admin interface listening on port 28017.

Step: 7. Connect to MongoDB

Web Service:
A Web Service is a code that is exposed over the network and can be invoked using HTTP.

Why Web Service:
Using web service your functionality can be exposed to rest of the world. Web service uses SOAP to transport data. It is a open protocol. With web service the functionality can be consumed from different platforms. For example you can create a web service in your windows computer and that can be consumed from your android mobile.

Using web service you can create a loosely coupled client server environment. Which means, when the server code is changed it is not always necessary to change the client code.

Axis 2
Axis 2 is a web service/SOAP/WSDL engine provided by Apache. It is a java based implementation. Axis 2 provides complete object model and modular architecture. Using Axis 2 you can easily create a web service from a plain java class, send SOAP messages, receive SOAP message.

Creating a web service from a plain java class in eclipse:

Step 1:
Before creating a project you need to add axis 2 dependencies to your eclipse.
To do so, download axis 2 from this website http://axis.apache.org/axis2/java/core/ .
Open your eclipse and go to Window>Preferences

Expand Web Services option and click Axis2 Preferences.
Give your axis2 location in the Axis2 runtime location box:

Click OK.

Step 2:
You have added Axis2 runtime to you eclipse. Now you can create your web service.
Go to File>New>Dynamic web project

Give any project name and select Dynamic web module version 2.5. Dynamic web module 3 is not compatible with Axis 2.

Now click finish.

Step 3:
Goto project properties and select Axis 2 facet.

Click OK. Now Axis 2 libraries will be imported to your project.

Step 4:
Now expand your project window>right click on src>New>Package

 

Give any name to the package;

Now click finish.

Step 5:
Create a new java class inside the newly created package:

Step 6:
Create a simple method which returns a String
/**
 * 
 */
package sample;

/**
 * @author Vienna
 *
 */
public class WebService {
 public String getName(){
  return "Test";
 }
}
And save the class.
Step 7:
Now right click on the java class>Web Services>Create new web service

Step 8:
Make sure that correct class name is selected in the Service implementation box.
In the configuration>Web service runtime> Make sure Axis 2 is selected. If it is different then click the name and a new window will be opened.

In the new window select Axis2

Now click OK and finish the setup.

Step 9:
Publish your project in Tomcat.

Step 10:
Run your project on tomcat.
To run the project Right click on the project name>Run as>Run on server>Select Tomcat>Click finish.
Now Axis home will be opened.

Now click “Services”
Under Web Service, your project url and the method you have created in the java class will be displayed. And the Service status should be active.

Now click Web Service, wsdl file will be displayed. Copy the URL of the WSDL file

Step 11:
Click web services explorer at the top of tool bar.

If this is not available in the tool bar then,
Right click on the tool bar and select customize perspective

Now make sure that the “Launch Web Services Explorer” check box is checked and click OK

After adding this “Web Services Explorer”, Open it.
Click WSDL page icon at the right corner of the wen services explorer window

Step 12:
Paste the WSDL url and click GO.
Your web service will be added to UDDI and it will be listed under UDDI registry.

Step 13:
Expand your project  name and click WebServiceSoap11Binding
The method name will be displayed at the right side

Step 14:
Click the method name displayed at the right side.

Now click “GO”

Step 15:
Now you should be seeing the String value returned by you method in the status window.

Step 16:
You have created your web service. You can use it in your other applications.

An Armstrong number is the one that equals the sum of its digits raised to the power of the number of digits in that number which is to be checked. To be more clear, let the number be n and the number of digits be x. We represent the number as nxnx-1nx-2…n3n2n1 where n1, n2, n3…nx are single digits 0-9. n is an Armstrong number if
n1x + n2x + n3x + nx-1x + nxx = n

153, 371, 9474 and 54748 are few Armstrong numbers.

153 = 13 + 53 + 33
371 = 33 +73 +13
9474 = 94 + 44 +74 + 44
54748 = 55 + 45 + 75 + 45 + 85

Java Program to check whether a given number is an Armstrong number
Let the number that is to be checked be stored in an int variable input. We make a copy of that input and store it in copyOfInput. It is required that we make a copy because the number to be checked will be changed during the execution of the program and towards the end, we need the original input number to declare whether it is an Armstrong number or not.

We first find the number of digits in the input number. To do so, we construct a String by concatenating the input number with a null string. We can also use the valueOf(int) method of the String class. The length of the resultant string obtaining using the length() method will give us the number of digits in the input number.

We also declare a variable sum and initialise it to zero. This variable will hold the sum of the digits raised to the appropriate powers.

Next, in a while loop, we extract the digits of the input from right to left, raise them to the appropriate power and add to the existing value of sum. To extract the last digit of the number, we find the remainder obtained don dividing that number by 10 using the modulo operator. The remainder is raised to the power numberOfDigits using the Math.pow() function. This function returns a double value which we explicitly cast to an int so that we can add it to the existing sum. Now, the last digit of copyOfInpuit will be truncated by diving it with 10. The while loop executes as long as copyOfInput is not zero. When it is zero, all the digits would have been processed.

Finally, we check if sum equals the input number. If it is so, the number is an Armstrong number. Given below is the complete code for this program.

import java.util.Scanner;

public class ArmstrongNumber {

public static boolean isArmstrong(int input) {
String inputAsString = input + “”;
int numberOfDigits = inputAsString.length();
int copyOfInput = input;
int sum = 0;
while (copyOfInput != 0) {
int lastDigit = copyOfInput % 10;
sum = sum + (int) Math.pow(lastDigit, numberOfDigits);
copyOfInput = copyOfInput / 10;
}
if (sum == input) {
return true;
} else {
return false;
}
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a number: “);
int inputNumber = scanner.nextInt();
boolean result = isArmstrong(inputNumber);
if (result) {
System.out.println(inputNumber + ” is an armstrong number”);
} else {
System.out.println(inputNumber + ” is not an armstrong number”);
}
}
}

Here are two sample executions of the program.

Enter a number: 153
153 is an armstrong number
Enter a number: 3479
3479 is not an armstrong number

Java Program to print Armstrong Numbers
Here is another Java program which takes a start and an end number and prints all the Armstrong numbers that lie between the above two numbers.

import java.util.Scanner;

public class ArmstrongNumber {

public static boolean isArmstrong(int input) {
String inputAsString = input + “”;
int numberOfDigits = inputAsString.length();
int copyOfInput = input;
int sum = 0;
while (copyOfInput != 0) {
int lastDigit = copyOfInput % 10;
sum = sum + (int) Math.pow(lastDigit, numberOfDigits);
copyOfInput = copyOfInput / 10;
}
if (sum == input) {
return true;
} else {
return false;
}
}

public static void printAll(int start, int end) {
System.out.println(“List of Armstrong Numbers between ” + start + ” and ” + end + ” :”);
for (int i = start; i <= end; i++) {
if (isArmstrong(i)) {
System.out.println(i);
}
}
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter start number: “);
int start = scanner.nextInt();
System.out.print(“Enter end number: “);
int end = scanner.nextInt();
printAll(start, end);
}
}

Here is a sample execution

Enter start number: 1
Enter end number: 3479
List of Armstrong Numbers between 1 and 3479 :
1
2
3
4
5
6
7
8
9
153
370
371
407
1634

The following sequence of numbers is known as Fibonacci numbers or sequence or series.

0, 1, 1, 2, 3, 5, 8, 13, 21 ….

To obtain the sequence, we start with 0 and 1 after which every number is the sum of the previous two numbers.

For example, the first two numbers will be 0 and 1

0, 1

To obtain the next number, we add the previous two numbers – 0 and 1 which gives one.

0, 1, 1

The next number would be 1 + 1 = 2

0, 1, 1, 2

Now, the next number would be 1 + 2 = 3

0, 1, 1, 2, 3

Continuing in this way gives the Fibonacci series. A particular term in the series is represented as Fnwhere n is the position of that number from the beginning. For example, F0 = 0, F1 = 1, F2 = 1, F3=2, F4 = 3, F5 = 5 and so on…

The Fibonacci series can be expressed as a recurrence relation as shown below:

F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2 ; n>=2

Printing the Fibonacci Series using Iteration
We will see how recursion can be used to print the Fibonacci Series. We will write a program which takes an input n and prints the first (n+1) terms of the Fibonacci series. n = 0 and n = 1 will be considered as special cases and the series for these input values of n will be printed directly. We will use two variables a and b which will hold the last two terms of the Fibonacci series that has already been printed. For example, after printing the first five terms of the sequence, i.e. 0, 1, 1, 2, 3; the value of a will be 2 and b will be 3. The next term in the sequence will be the sum of a and b. Now, the values of a and b should be updated so that they will again hold the last two terms that were printed. To do so, we copy b to a, and the sum of the previous values of a and b to b. The loop will be repeated n-1 times.

The program is given below.

import java.util.Scanner;

public class FibonacciSeries {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(“Enter the value of n: “);
int n = s.nextInt();
fibonacci(n);
}

public static void fibonacci(int n) {
if (n == 0) {
System.out.println(“0”);
} else if (n == 1) {
System.out.println(“0 1”);
} else {
System.out.print(“0 1 “);
int a = 0;
int b = 1;
for (int i = 1; i < n; i++) {
int nextNumber = a + b;
System.out.print(nextNumber + ” “);
a = b;
b = nextNumber;
}
}
}
}

Here is a sample execution

Enter the value of n: 7
0 1 1 2 3 5 8 13

Fibonacci Series using Recursion
The recursive definition of Fibonacci Series has already been stated at the start of this article. The Java program is given below.

import java.util.Scanner;

public class FibonacciSeries {

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print(“Enter the value of n: “);
int n = s.nextInt();
for (int i = 0; i <= n; i++) {
System.out.print(fibonacci(i) + ” “);
}
}

public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n – 1) + fibonacci(n – 2);
}
}
}