MongoDb in Java Example. How to use MongoDb database in java. Insert,Update,Delete And how to deal with date in mongodb.And it also shows InsertMany,InsertOne,findOneByCondition,findByDate,UpdateOne,UpdateOneByMultipleCondition,DeleteOne,DeleteMany


MongoDb exmaple in java. This example demonstrates than how to deal with date in MongoDb and how to query with date from to date's
or greater than or less than date. 


Main file:


public class Main {

public static void main(String[] args) {
    // write your code here

    DataBaseOperation.InsertMany();
    DataBaseOperation.InsertOne();

    DataBaseOperation.findOne();
    DataBaseOperation.findOneByCondition();
    DataBaseOperation.findAll();
    DataBaseOperation.findByDate();

    DataBaseOperation.UpdateOneByName();
    DataBaseOperation.UpdateOneByMultipleCondition();
    DataBaseOperation.UpdateManyByName();

    DataBaseOperation.DeleteOne();
    DataBaseOperation.DeleteOneByName();
    DataBaseOperation.DeleteManyByName();




     }
 }


DataBaseOperation.java


 import com.mongodb.BasicDBObject;
 import com.mongodb.DBCursor;
 import com.mongodb.DBObject;
 import com.mongodb.client.FindIterable;
 import com.mongodb.client.MongoCollection;
 import com.mongodb.client.MongoCursor;
 import com.mongodb.client.result.UpdateResult;
 import org.bson.Document;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 import static com.krunal.MongoDb.Utility.*;
  import static com.mongodb.client.model.Filters.and;
public class DataBaseOperation {

     public static void InsertMany() {

         MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
              .getCollection("Test");

         List<Document> insertMany = new ArrayList<>();
          insertMany.add(new Document("Name", "Jay").append("age", 30)
            .append("Birthday",getDateFromDD_MM_YYYY("02/03/1996")));
        insertMany.add(new Document("Name", "neel").append("age", 33)
              .append("Birthday",getDateFromDD_MM_YYYY("10/06/1998")));
        insertMany.add(new Document("Name", "neel").append("age", 44)
            .append("Birthday",getDateFromDD_MM_YYYY("27/05/1996")));
        insertMany.add(new Document("Name", "neel").append("age", 45)
             .append("Birthday",getDateFromDD_MM_YYYY("04/05/1992")));
        insertMany.add(new Document("Name", "Karan").append("age", 100)
              .append("Birthday",getDateFromDD_MM_YYYY("01/01/1991")));


       TestCollection1.insertMany(insertMany);
  }


public static void InsertOne() {
    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

    // To insert current Datetime.
    TestCollection1.insertOne(new Document("Name", "meet").append("age", 34)
            .append("Birthday",new Date()));
}

public static void findOne() {
    // find one By name Document Object.

    // Select * from Test where Name = 'neel' LIMIT 1

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

    Document insertQuery = Document.parse("{'Name': \"neel\"}");

    FindIterable<Document> list = TestCollection1.find(insertQuery).limit(1);

    MongoCursor<Document> cursor = list.iterator();
    try {

        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }


}

public static void findOneByCondition() {

    // Select * from Test where Name = 'neel' and age > 36

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

     //      Document query = Document.parse("{$and: [{ age: { $gt: 36 }},{'Name': 
                \"neel\"}]}");

    Document query = Document.parse("{\"Name\": \"neel\",\"age\": {\"$gt\": 38}}");

    // Both above query work same.
    // http://www.querymongo.com/
    // for converting MySQL queries to MongoDB syntax.

    FindIterable<Document> list = TestCollection1.find(query);


    MongoCursor<Document> cursor = list.iterator();

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }


}

public static void findByDate() {

    // Select * from Test where Birthday BETWEEN '1992-05-04' AND '1996-05-27'

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

    Document query = Document.parse("{Birthday: {$gte: ISODate('"
            + queryDateConversion("04/05/1992") + "')"
            +", $lte: ISODate('" + queryDateConversion("27/05/1996") + "')}}");

    FindIterable<Document> list = TestCollection1.find(query);

    try {
        if (list != null){
            for (Document item : list){
                System.out.println("_id:- " + item.get("_id"));
                System.out.println("Birthday:- " + getDD_MM_YYYYFromDate((Date)
                        item.get("Birthday")));
                System.out.println("Name:- " + item.get("Name"));
                System.out.println("age:- " + item.get("age"));
                System.out.println("---------------------------------------");
            }
        }
    }catch (Exception e){
        System.out.println("Exception:- " + e.getMessage());

    }

}

public static void findAll() {

    // Select * from Test

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

    FindIterable<Document> list = TestCollection1.find();

    try {
        if (list != null){
            for (Document item : list){
                System.out.println("_id:- " + item.get("_id"));
                System.out.println("Birthday:- " + getDD_MM_YYYYFromDate((Date)
                        item.get("Birthday")));
                System.out.println("Name:- " + item.get("Name"));
                System.out.println("age:- " + item.get("age"));
                System.out.println("---------------------------------------");
            }
        }
    }catch (Exception e){
        System.out.println("Exception:- " + e.getMessage());

    }
}


public static void UpdateOneByName() {

    // UPDATE Test SET age = 98, Name = 'Karan patel' where Name IN (SELECT Name
    //                FROM Test
    //                WHERE Name = 'Karan'
    //                ORDER BY Name asc
    //                LIMIT 1)

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

    // filter query.
    Document queryByName = Document.parse("{Name: 'Karan'}");

    // query to update new values.
    Document querySet = Document.parse("{ $set: { age: '98',Name: 'Karan patel'}}");

    UpdateResult updateResult = TestCollection1.updateOne(queryByName, querySet);

    System.out.println(updateResult);

}

public static void UpdateOneByMultipleCondition() {

    // UPDATE  Test SET age = 98, Name = 'Karan patel' where Name = 'neel' and age = 
                33

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

    // filter query.
    Document queryByName = Document.parse("{Name: 'neel',age: 33}");

    // query to update new values.
    Document querySet = Document.parse("{ $set: { age: '200',Name: 'sarth'}}");

    UpdateResult updateResult = TestCollection1.updateMany(queryByName, querySet);

    System.out.println(updateResult);

}


public static void UpdateManyByName() {

    // UPDATE  Test SET age = 98, Name = 'Karan patel' where Name = 'Karan'

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");

    // filter query.
    Document queryByName = Document.parse("{Name: 'neel'}");

    // query to update new values.
    Document querySet = Document.parse("{ $set: { age: '98',Name: 'parth'}}");

       UpdateResult updateResult = TestCollection1.updateMany(queryByName, querySet);

      System.out.println(updateResult);

 }

  public static void DeleteOne() {
     // Delete By Hole Document Object.
     // DELETE FROM Test where Name= 'Jay' and age = 30
      MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");


     TestCollection1.deleteOne(new Document("Name", "Jay").append("age", 30));
 }

public static void DeleteOneByName() {
    // Delete One By name Document Object.
    // Please Note than this method will only delete Single Record with name "neel"
    // even if there are many "neel" records in the collection.

    // DELETE FROM Test where Name in (SELECT Name FROM Test WHERE Name = 'neel'
    // ORDER BY Name asc LIMIT 1 )

    MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");


    TestCollection1.deleteOne(new Document("Name", "neel"));
  }

   public static void DeleteManyByName() {
      // Delete Many By name Document Object.

      // DELETE FROM Test where Name= 'neel'
     MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");


      TestCollection1.deleteMany(new Document("Name", "neel"));
  }


  public static void Drop_Test_Collection(){

      MongoCollection<Document> TestCollection1 = MongoDbClient.getInstance()
            .getCollection("Test");
           TestCollection1.drop();
   }


}

Utility.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Utility {


/**
 * Get Date from string dd-mm-yyyy.
 *
 * @param dateString
 * @return Date.
 */
public static Date getDateFromDD_MM_YYYY(String dateString) {
    Date date = null;
    try {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

        date = formatter.parse(dateString);
    } catch (Exception e) {
        System.out.println("Exception getDateFromDD_MM_YYYY:- " + e.getMessage());
    }
    return date;
}

/**
 * Get dd-mm-yyyy from Date.
 *
 * @param date
 * @return String.
 */
public static String getDD_MM_YYYYFromDate(Date date) {
    String strDate = "";
    try {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        strDate = formatter.format(date);
    } catch (Exception e) {
        System.out.println("Exception getDD_MM_YYYYFromDate:- " + e.getMessage());
    }
    return strDate;
 }


  /**
   * This Method convert dd/MM/YYYY string to yyyy-MM-dd string
   * because for querying date in MongoDb it needs yyyy-MM-dd string.
   * not dd/MM/YYYY string.
   * @param dd_MM_YYYY
   * @return String.
   */
  public static String queryDateConversion(String dd_MM_YYYY) {
      String strDate = "";
      try {
        strDate = new SimpleDateFormat("yyyy-MM-dd")
                .format(getDateFromDD_MM_YYYY(dd_MM_YYYY));

      } catch (Exception e) {
          System.out.println("Exception queryDateConversion:- " + e.getMessage());
      }
      return strDate;
   }



 }

MongoDbClient.java

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.io.Serializable;

public class MongoDbClient implements Serializable {

private static MongoClient mClient;
private final static String TestDb = "JavaDemoDb";
private volatile static MongoDbClient mINSTANCE = null;


private MongoDbClient(){}

public static MongoDbClient getInstance() {
    if (mINSTANCE == null) {
        synchronized (MongoDbClient.class){
            if (mINSTANCE == null){
                mINSTANCE = new MongoDbClient();
            }
        }
    }
    return mINSTANCE;
}


// Singleton for MongoClient
// Creates a single connection pool internally
private MongoClient getMongoClientConnection() {
    if (mClient == null) {
        mClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
    }
    return mClient;
}


// Utility method to get database instance
public MongoDatabase getDB() {
    return getMongoClientConnection().getDatabase(TestDb);
}


// Utility method to get user collection
public MongoCollection<Document> getCollection(String collectionName) {
    return getDB().getCollection(collectionName);
}



// implement readResolve method

  protected Object readResolve()
  {
    return mINSTANCE;
   }

  //    @Override
   //    public int hashCode() {
   //        return super.hashCode();
   //    }
}


Comments

Popular posts from this blog

Error:java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant). at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:240) at com.google.android.material.internal.ThemeEnforcement.checkMaterialTheme(ThemeEnforcement.java:215) at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:143) at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:78) at com.google.android.material.chip.ChipDrawable.loadFromAttributes(ChipDrawable.java:359) at com.google.android.material.chip.ChipDrawable.createFromAttributes(ChipDrawable.java:292) at com.google.android.material.chip.Chip.(Chip.java:193) at com.google.android.material.chip.Chip.(Chip.java:186) at com.google.android.material.chip.Chip.(Chip.java:182) at com.demo.nspl.restaurantlite.Navigation_Drawer.SalesFragment.getFilterChip(SalesFragment.java:158) at com.demo.nspl.restaurantlite.Navigation_Drawer.SalesFragment.lambda$onCreateView$0(SalesFragment.java:71) at com.demo.nspl.restaurantlite.Navigation_Drawer.-$$Lambda$SalesFragment$KCm-iiczjdYbpiNmaNw12gtFOoQ.onClick(lambda) at android.view.View.performClick(View.java:5268) at android.view.View$PerformClick.run(View.java:21550) at android.os.Handler.handleCallback(Handler.java:822) at android.os.Handler.dispatchMessage(Handler.java:104) at android.os.Looper.loop(Looper.java:207) at android.app.ActivityThread.main(ActivityThread.java:5811) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)

Configuration 'androidTestCompile' is obsolete and has been replaced with 'androidTestImplementation' and 'androidTestApi'. It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'. It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html Configuration 'androidTestApi' is obsolete and has been replaced with 'androidTestImplementation'. It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html Configuration 'testCompile' is obsolete and has been replaced with 'testImplementation' and 'testApi'. It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html Configuration 'testApi' is obsolete and has been replaced with 'testImplementation'. It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html