MongoDB - Java Driver
CRUD in Java
- insert()
- find()
- update()
- remove()
DBObject is a main interface used by Java driver. Essentially a key/value data store.
BasicDBObject is a general purpose implementation which extendsLinkedHashMap.
Example:
import com.mongodb.BasicDBObject;
public class BasicDBObjectExample {
public static void main(String[] args) {
BasicDBObject basicDBObject = new BasicDBObject();
basicDBObject.put("name","Shiv");
basicDBObject.put("age",33);
basicDBObject.put("address",new BasicDBObject("street","East Street")
.append("block","2nd block")
);
System.out.println(basicDBObject);
}
}
Output
{ "name" : "Shiv" , "age" : 33 , "address" : { "street" : "East Street" , "block" : "2nd block"}}
Insert
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
public class InsertExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection users = test.getCollection("users");
DBObject newUser = new BasicDBObject().append("name","clark");
System.out.println("Before insert - " + newUser);
users.insert(newUser);
System.out.println("After insert (Notice _id field) - " + newUser);
}
}
Output:
Before insert - { "name" : "clark"}
After insert (Notice _id field) - { "name" : "clark" , "_id" : { "$oid" : "51c5a08e036476fa1d8ba516"}}
- MongoDB .insert() would add _id field if doc isn't having one.
- If you try to insert again the same document (same id), you would get an _MongoException$DuplicateKey exception.
- You can even insert a list of document.
Find
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
public class FindExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection people = test.getCollection("people");
System.out.println("Finds any object from collection - " + people.findOne());
System.out.println("Collection Count - "+people.count());
try(DBCursor cursor = people.find()){
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
System.out.println("Count - "+cursor.count());
}
}
}
Output:
Finds any object from collection - { "_id" : { "$oid" : "51b314985fb1aa4bb04952d0"} , "age" : 21.0 , "name" : "Bobby" , "title" : "Dr"}
{ "_id" : { "$oid" : "51b314985fb1aa4bb04952d0"} , "age" : 21.0 , "name" : "Bobby" , "title" : "Dr"}
{ "_id" : { "$oid" : "51b3149d5fb1aa4bb04952d1"} , "name" : "Chris" , "title" : "Dr"}
{ "_id" : { "$oid" : "51b314a15fb1aa4bb04952d2"} , "name" : "Don" , "title" : "Dr"}
Count - 3
- .findOne() - is similar to the one available on shell. Returns a random object from collection.
- .find() - This returns a cursor reference. Since DBCursor is implementing Iterator, we can use next(),hasNext() etc methods.
- .count() - This gives us no of docs in a cursor.
Query using Criteria
Sample Collection:
> db.accounts.find();
{ "_id" : ObjectId("51b31e1cd8f5f032e5970603"), "name" : "Howard", "favorites" : [ "pretzels", "beer" ] }
{ "_id" : ObjectId("51b31e2ed8f5f032e5970604"), "name" : "George", "favorites" : [ "pretzels", "ice cream" ] }
{ "_id" : ObjectId("51b31f38d8f5f032e5970605"), "name" : "Sam", "favorites" : "beer" }
{ "_id" : ObjectId("51b337c8d8f5f032e5970606"), "name" : "John", "favorites" : [ "beer", "cheese" ] }
{ "_id" : ObjectId("51b337e2d8f5f032e5970607"), "name" : "Irving", "favorites" : [ "beer", "cheese", "pretzels" ] }
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
import java.util.Arrays;
public class QueryCriteriaExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection accounts = test.getCollection("accounts");
DBObject query = new BasicDBObject("favorites",new BasicDBObject("$all",Arrays.asList("beer")));
System.out.println("Using BasicDBObject - ");
try(DBCursor cursor = accounts.find(query)){
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
}
QueryBuilder builder = QueryBuilder.start("favorites").all(Arrays.asList("beer"));
System.out.println("Using QueryBuilder - ");
try(DBCursor cursor = accounts.find(builder.get())){
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
}
}
}
Output:
Using BasicDBObject -
{ "_id" : { "$oid" : "51b31e1cd8f5f032e5970603"} , "name" : "Howard" , "favorites" : [ "pretzels" , "beer"]}
{ "_id" : { "$oid" : "51b31f38d8f5f032e5970605"} , "name" : "Sam" , "favorites" : "beer"}
{ "_id" : { "$oid" : "51b337c8d8f5f032e5970606"} , "name" : "John" , "favorites" : [ "beer" , "cheese"]}
{ "_id" : { "$oid" : "51b337e2d8f5f032e5970607"} , "name" : "Irving" , "favorites" : [ "beer" , "cheese" , "pretzels"]}
Using QueryBuilder -
{ "_id" : { "$oid" : "51b31e1cd8f5f032e5970603"} , "name" : "Howard" , "favorites" : [ "pretzels" , "beer"]}
{ "_id" : { "$oid" : "51b31f38d8f5f032e5970605"} , "name" : "Sam" , "favorites" : "beer"}
{ "_id" : { "$oid" : "51b337c8d8f5f032e5970606"} , "name" : "John" , "favorites" : [ "beer" , "cheese"]}
{ "_id" : { "$oid" : "51b337e2d8f5f032e5970607"} , "name" : "Irving" , "favorites" : [ "beer" , "cheese" , "pretzels"]}
- Query by example - Using BasicDBObject, we can create a query and pass it on to find method.
- QueryBuilder - Provides various functions to build query.
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
import java.util.Arrays;
public class FieldSelectionExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection accounts = test.getCollection("accounts");
QueryBuilder builder = QueryBuilder.start("favorites").all(Arrays.asList("beer"));
try(DBCursor cursor = accounts.find(builder.get(),new BasicDBObject("name",true).append("_id",0))){
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
}
}
}
Output:
{ "name" : "Howard"}
{ "name" : "Sam"}
{ "name" : "John"}
{ "name" : "Irving"}
- Field Selection - By providing a list of keys to be returned in result.
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
public class DotNotationExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection accounts = test.getCollection("users");
QueryBuilder builder = QueryBuilder.start("address.zip").is(51605);
try (DBCursor cursor = accounts.find(builder.get())) {
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
}
}
}
Output:
{ "_id" : "shiv" , "address" : { "street" : "East street" , "block" : "2nd block" , "zip" : 51605.0}}
{ "_id" : "neo" , "address" : { "street" : "West street" , "block" : "3rd block" , "zip" : 51605.0}}
- Using . notation - In case of nested documents, using a dot notation we can provide query criteria as well as in field selection.
Sample Collection
> db.users.find()
{ "_id" : "clark" }
{ "_id" : "shiv", "address" : { "street" : "East street", "block" : "2nd block", "zip" : 51605 } }
{ "_id" : "neo", "address" : { "street" : "West street", "block" : "3rd block", "zip" : 51605 } }
{ "_id" : "sam", "address" : { "street" : "Main street", "block" : "1st block", "zip" : 21605 } }
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
public class SortSkipExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection accounts = test.getCollection("users");
QueryBuilder builder = QueryBuilder.start();
DBCursor cursor = accounts.find(builder.get())
.sort(new BasicDBObject("_id",-1))
.skip(1)
.limit(3);
try{
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
}finally {
cursor.close();
}
}
}
Output:
{ "_id" : "sam" , "address" : { "street" : "Main street" , "block" : "1st block" , "zip" : 21605.0}}
{ "_id" : "neo" , "address" : { "street" : "West street" , "block" : "3rd block" , "zip" : 51605.0}}
{ "_id" : "clark"}
- .sort() .skip() .limit() - These method are chained method calls on .find() method which returns a cursor.
Update
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
public class UpdateExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection users = test.getCollection("users");
// replaces existing documents
users.update(new BasicDBObject("_id","clark"),new BasicDBObject("age",40));
// to add field to existing document
users.update(new BasicDBObject("_id","clark"),new BasicDBObject("$set",new BasicDBObject("sex","M")));
// since mark doesn't exist below will not have any affect
users.update(new BasicDBObject("_id","mark"),new BasicDBObject("$set",new BasicDBObject("sex","M")));
// but if we use upsert or saveOrUpdate()
// update() api will insert new row
users.update(new BasicDBObject("_id","rahul"),new BasicDBObject("$set",new BasicDBObject("sex","M")),true,false);
// default behaviour of update() is that it will only update 1 row
// if you would like to update more records, then the multi param comes in
users.update(new BasicDBObject(),new BasicDBObject("$set",new BasicDBObject("title","Dr.")),false,true);
printAll(users);
}
private static void printAll(DBCollection users) {
QueryBuilder builder = QueryBuilder.start();
DBCursor cursor = users.find(builder.get());
try{
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
}finally {
cursor.close();
}
}
}
Output:
{ "_id" : "shiv" , "address" : { "street" : "East street" , "block" : "2nd block" , "zip" : 51605.0} , "title" : "Dr."}
{ "_id" : "neo" , "address" : { "street" : "West street" , "block" : "3rd block" , "zip" : 51605.0} , "title" : "Dr."}
{ "_id" : "sam" , "address" : { "street" : "Main street" , "block" : "1st block" , "zip" : 21605.0} , "title" : "Dr."}
{ "_id" : "clark" , "age" : 40 , "sex" : "M" , "title" : "Dr."}
{ "_id" : "rahul" , "sex" : "M" , "title" : "Dr."}
- Update() api works similar to shell update function.
- By default it will only update first matching record unless you specify multi = true.
- You can make update behave like a saveOrUpdate() using upsert = true.
- If you didn't use $set operator, the new document will replace existing document.
Remove
Example:
import com.mongodb.*;
import java.net.UnknownHostException;
public class RemoveExample {
public static void main(String[] args) throws UnknownHostException {
Mongo client = new Mongo();
DB test = client.getDB("test");
DBCollection users = test.getCollection("users");
// removes all records matching criteria
users.remove(new BasicDBObject("_id","clark"));
printAll(users);
}
private static void printAll(DBCollection users) {
QueryBuilder builder = QueryBuilder.start();
DBCursor cursor = users.find(builder.get());
try{
for (DBObject dbObject : cursor) {
System.out.println(dbObject);
}
}finally {
cursor.close();
}
}
}
Output:
{ "_id" : "shiv" , "address" : { "street" : "East street" , "block" : "2nd block" , "zip" : 51605.0} , "title" : "Dr."}
{ "_id" : "neo" , "address" : { "street" : "West street" , "block" : "3rd block" , "zip" : 51605.0} , "title" : "Dr."}
{ "_id" : "sam" , "address" : { "street" : "Main street" , "block" : "1st block" , "zip" : 21605.0} , "title" : "Dr."}
{ "_id" : "rahul" , "sex" : "M" , "title" : "Dr."}
- The main difference between default behavior of remove() and update() api is that the remove() will remove all documents which match criteria whereas update() only removes first document which matches criteia.
- Another api findAndModify() allows you to find and modify the documents in same transaction.
출처 : http://scriptogr.am/shiv/post/mongodb-java-driver
'Industry 4.0 > Big Data' 카테고리의 다른 글
PINPOINT 란 (0) | 2017.03.02 |
---|---|
[MongoDB] mongo-2.10.1.jar, junit 쓴 단위 테스트 for JAVA (0) | 2014.12.13 |
[MongoDB] MongoDB 에서 Sequence 사용하기 (0) | 2014.10.07 |
[MongoDB] how to use “find” to search “_id => OBjectID(”id“)” in Perl API (2) | 2014.10.01 |
[MongoDB] Sequence 사용하기 (0) | 2014.09.22 |
댓글