MongoDB : A Quick Sample through Java
Below is the working sample to interact with MongoDB to fetch the data from it. Attached are the sample files to load the data in DB. You can use it to import the data to MongoDB using mongoimport command.
package mongoPrac;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
/**
* @author Nitin Agrawal
*
*/
public class MongoConnection {
public static void main(String[] args) {
// If MongoDB connection to be made to local MongoDB server.
// MongoClient mongo = new MongoClient("localhost", 27017);
// If MongoDB connection to be made to remote MongoDB server then give the address of the remote server where MongoDB is running.
MongoClient mongo = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
// If we want to know the names of databases created in MongoDB then can use below method but it is deprecated now,
// so use the way shown in next line.
List<String> dbs = mongo.getDatabaseNames();
MongoIterable<String> mongoIterable = mongo.listDatabaseNames();
Iterator<String> itr = mongoIterable.iterator();
while(itr.hasNext())
System.out.println(itr.next());
// To connect to the database or one of the databases in MongoDB
MongoDatabase mongoDatabase = mongo.getDatabase("test");
// To connect to the collection in the above database & then getting the count of all the records in that collection.
System.out.println(mongoDatabase.getCollection("cities").count());
// Connecting to other collection in the same database above.
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("products");
// As everything in MongoDB is document so is its search criteria, you have to create a new document like below simple one.
Document document = new Document("shipping_details.weight", 350);
// Provide the above created document to get the count of the required records.
System.out.println(mongoCollection.count(document));
// Below first records are fetched on the basis of the filter & then sort that list of records on the basis of another criteria.
FindIterable<Document> findIterable = mongoCollection.find(document).sort(new Document("title", 1));
// Iterating through each document fetched above.
findIterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
// Usage of other operators like less than.
System.out.println(mongoCollection.count(new Document("shipping_details.weight", new Document("$lt", 250))));
// Below is a way to combine multiple conditions to get the required records from the collection
MongoCollection<Document> cities = mongoDatabase.getCollection("cities");
Document document1 = new Document("city", "AGAWAM");
Document document3 = new Document("city", "BARRE");
List<Document> ls = new ArrayList<>();
ls.add(document1);
ls.add(document3);
Document document4 = new Document("$or", ls);
Document document2 = new Document("state", "MA");
List<Document> ls1 = new ArrayList<>();
ls1.add(document4);
ls1.add(document2);
Document and = new Document("$and", ls1);
System.out.println(cities.count(and));
// Always close the mongo db connection after completing the task
mongo.close();
}
}
Below is the code to insert, update & delete the documents :
package mongoPrac;
import java.math.BigDecimal;
import org.bson.Document;
import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
/**
* @author nitin_agrawal
* Below Gson library is used to convert the java object to Json.
*
*/
public class MavenCRUD {
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongo.getDatabase("test");
MongoCollection<Document> productsCollection = mongoDatabase.getCollection("products");
Gson gson = new Gson();
Product product = new Product();
product.setName("Micromax Nitro2");
product.setPrdNo(85780l);
product.setPrice(new BigDecimal(10000.95));
Product product2 = new Product();
product2.setName("Micromax Nitro2");
product2.setPrdNo(85780l);
product2.setPrice(new BigDecimal(8000.95));
Document document = new Document();
// Below way we can use to set the key value pairs in document to store in MongoDB.
/*document.put("Name", "Micromax Nitro2");
document.put("PrdNo", "85780l");
document.put("Price", new BigDecimal(6000.95).toString());*/
String json = gson.toJson(product);
document = Document.parse(json);
System.out.println(document.getString("Name"));
// Below is a way to insert the new document into MongoDB.
productsCollection.insertOne(document);
System.out.println(productsCollection.count());
// Below is the way to delete all the documents matching to the given criteria else if want to delete only one such document
// then use deleteOne so that only first matching document will be deleted.
productsCollection.deleteMany(new Document("Name", "Micromax Nitro2"));
// Below is the way to get the count of the documents satisfying the given criteria.
System.out.println(productsCollection.count(new Document("Name", "Micromax Nitro2")));
Document doc = Document.parse(gson.toJson(product2));
// Below is a way to update the existing record by replacing it with the new document after searching the document with given criteria.
productsCollection.replaceOne(new Document("Name", "Micromax Nitro2"), doc);
// Below checking if the document is updated with new price given.
System.out.println(productsCollection.find(new Document("Name", "Micromax Nitro2")).first().get("Price"));
// Always close the mongo db connection after completing the task
mongo.close();
}
}
Below is the POJO class used in above code.
package mongoPrac;
import java.math.BigDecimal;
import com.google.gson.annotations.SerializedName;
public class Product {
// This annotation is used to give the custom name to the fields in JSON which are then reflected in MongoDB
@SerializedName("Product Number")
private long prdNo;
@SerializedName("Name")
private String name;
@SerializedName("Price")
private BigDecimal price;
public long getPrdNo() {
return prdNo;
}
public void setPrdNo(long prdNo) {
this.prdNo = prdNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
package mongoPrac;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
/**
* @author Nitin Agrawal
*
*/
public class MongoConnection {
public static void main(String[] args) {
// If MongoDB connection to be made to local MongoDB server.
// MongoClient mongo = new MongoClient("localhost", 27017);
// If MongoDB connection to be made to remote MongoDB server then give the address of the remote server where MongoDB is running.
MongoClient mongo = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
// If we want to know the names of databases created in MongoDB then can use below method but it is deprecated now,
// so use the way shown in next line.
List<String> dbs = mongo.getDatabaseNames();
MongoIterable<String> mongoIterable = mongo.listDatabaseNames();
Iterator<String> itr = mongoIterable.iterator();
while(itr.hasNext())
System.out.println(itr.next());
// To connect to the database or one of the databases in MongoDB
MongoDatabase mongoDatabase = mongo.getDatabase("test");
// To connect to the collection in the above database & then getting the count of all the records in that collection.
System.out.println(mongoDatabase.getCollection("cities").count());
// Connecting to other collection in the same database above.
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("products");
// As everything in MongoDB is document so is its search criteria, you have to create a new document like below simple one.
Document document = new Document("shipping_details.weight", 350);
// Provide the above created document to get the count of the required records.
System.out.println(mongoCollection.count(document));
// Below first records are fetched on the basis of the filter & then sort that list of records on the basis of another criteria.
FindIterable<Document> findIterable = mongoCollection.find(document).sort(new Document("title", 1));
// Iterating through each document fetched above.
findIterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
// Usage of other operators like less than.
System.out.println(mongoCollection.count(new Document("shipping_details.weight", new Document("$lt", 250))));
// Below is a way to combine multiple conditions to get the required records from the collection
MongoCollection<Document> cities = mongoDatabase.getCollection("cities");
Document document1 = new Document("city", "AGAWAM");
Document document3 = new Document("city", "BARRE");
List<Document> ls = new ArrayList<>();
ls.add(document1);
ls.add(document3);
Document document4 = new Document("$or", ls);
Document document2 = new Document("state", "MA");
List<Document> ls1 = new ArrayList<>();
ls1.add(document4);
ls1.add(document2);
Document and = new Document("$and", ls1);
System.out.println(cities.count(and));
// Always close the mongo db connection after completing the task
mongo.close();
}
}
Below is the code to insert, update & delete the documents :
package mongoPrac;
import java.math.BigDecimal;
import org.bson.Document;
import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
/**
* @author nitin_agrawal
* Below Gson library is used to convert the java object to Json.
*
*/
public class MavenCRUD {
public static void main(String[] args) {
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongo.getDatabase("test");
MongoCollection<Document> productsCollection = mongoDatabase.getCollection("products");
Gson gson = new Gson();
Product product = new Product();
product.setName("Micromax Nitro2");
product.setPrdNo(85780l);
product.setPrice(new BigDecimal(10000.95));
Product product2 = new Product();
product2.setName("Micromax Nitro2");
product2.setPrdNo(85780l);
product2.setPrice(new BigDecimal(8000.95));
Document document = new Document();
// Below way we can use to set the key value pairs in document to store in MongoDB.
/*document.put("Name", "Micromax Nitro2");
document.put("PrdNo", "85780l");
document.put("Price", new BigDecimal(6000.95).toString());*/
String json = gson.toJson(product);
document = Document.parse(json);
System.out.println(document.getString("Name"));
// Below is a way to insert the new document into MongoDB.
productsCollection.insertOne(document);
System.out.println(productsCollection.count());
// Below is the way to delete all the documents matching to the given criteria else if want to delete only one such document
// then use deleteOne so that only first matching document will be deleted.
productsCollection.deleteMany(new Document("Name", "Micromax Nitro2"));
// Below is the way to get the count of the documents satisfying the given criteria.
System.out.println(productsCollection.count(new Document("Name", "Micromax Nitro2")));
Document doc = Document.parse(gson.toJson(product2));
// Below is a way to update the existing record by replacing it with the new document after searching the document with given criteria.
productsCollection.replaceOne(new Document("Name", "Micromax Nitro2"), doc);
// Below checking if the document is updated with new price given.
System.out.println(productsCollection.find(new Document("Name", "Micromax Nitro2")).first().get("Price"));
// Always close the mongo db connection after completing the task
mongo.close();
}
}
Below is the POJO class used in above code.
package mongoPrac;
import java.math.BigDecimal;
import com.google.gson.annotations.SerializedName;
public class Product {
// This annotation is used to give the custom name to the fields in JSON which are then reflected in MongoDB
@SerializedName("Product Number")
private long prdNo;
@SerializedName("Name")
private String name;
@SerializedName("Price")
private BigDecimal price;
public long getPrdNo() {
return prdNo;
}
public void setPrdNo(long prdNo) {
this.prdNo = prdNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
|
|