To connect MongoDB through JAVA, we will use MongoClient and to fetch and iterate data we will use MongoCollection and FindIterable classes.
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.
Full example of MongoDB connection in JAVA
Employee Collection
{
"_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"
}
}
JAVA code for Mongo Connection and fetching the data.
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());
}
}
}
The above code will connect to mongo and fetch data from employee collection as per the given criteria.
No comments:
Post a Comment