понедельник, 3 февраля 2014 г.

CRUD operation in Java Driver.

Теперь рассмотрим эти же операции для Java:
insert(DBObject)
 Для добавления в коллекцию нужно создать объект BasicDBObject:
BasicDBObject doc = new BasicDBObject();
И, собственно добавление:
doc.put("username", "jyemin");
doc.put("birthDate", new Date(2345));
doc.put("programmer", true);
doc.put("age", 8);
doc.put("language", Arrays.asList("Java","C++"));
doc.put("address", new BasicDBObject("street", "20 Main").append("town","West").append("zip","56789"));

Quiz: Java Driver: Representing Documents


How would you create a document using the Java driver with this JSON structure:
{
   "_id" : "user1",
   "interests" : [ "basketball", "drumming"]
}
Добавление в коллекцию:
MongoClient client = new MongoClient();
DB courseDB = cclient.getDB("course");
DBcollection collection = courseDB.getCollection("insertTest"); 
DBObject doc = new BasicDBObject().append("x",1);
DBObject doc2 = new BasicDBObject().append("x,2);
collection.insert(doc);
collection.insert(Arrays.asList(doc,doc2));
Но если мы попробуем дважды добавить один документ вылетит эксепшн.
Для очистки коллекции нужно следующее:
collection.drop();

Quiz: Java Driver: Insert

Do you expect the second insert below to succeed?
        MongoClient client = new MongoClient();
        DB db = client.getDB("school");
        DBCollection people = db.getCollection("people");

        DBObject doc = new BasicDBObject("name", "Andrew Erlichson")
                .append("company", "10gen");

        try {
            people.insert(doc);      // first insert
            doc.removeField("_id");  // remove the "_id" field
            people.insert(doc);      // second insert
        } catch (Exception e) {
            e.printStackTrace();
        }
Java Driver: find(), findOne(), count().
Чтобы присвоить переменной элемент коллекции нужно:
DBObject one = collection.findOne();
А для того, чтобы пройтись по всей коллекции и, например, вывести все документы нужно:
DBCursor cursor = collection.find();try{while(cursor.hasNext()){DBObject cur = cursor.next();System.out.println(cur);}finally{cursor.close();}
Для подсчета документов существует функция count():
long count = collection.count();

Quiz: Java Driver: find, findOne, count

In the following code snippet:
        MongoClient client = new MongoClient();
        DB db = client.getDB("school");
        DBCollection people = db.getCollection("people");
        DBObject doc;
        xxxx
        System.out.println(doc);
Please enter the simplest one line of Java code that would be needed in place of xxxx to make it print one document from the people collection.

doc = people.findOne();

Поиск по каким-то критериям.
Если нам нужно сделать выборку каких либо конкретных элементов мы можем добавить в код, который приводился выше кое-какие изменения:
DBObject query = new DBObject("x",0);
DBCursor cursor = collection.find(query);
try{while(cursor.hasNext()){DBObject cur = cursor.next();System.out.println(cur);}finally{cursor.close();}
И для подсчета количества:
long count = collection.count(query);

Есть еще один вариант поиска:
QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThen(10).lessThen(70);
и подставим builder.get() вместо query.

Quiz: Java Driver: Query Criteria

Given a collection of documents with two fields -- type and score -- what is the correct line of code to find all documents where type is "quiz" and score is greater than 20 and less than 90. Select all that apply.
sort(), limit() и skip():
Для сортировки нам необходимо при создании курсора добавить skip()/limit()/sort():
DBCursor cursor = collection.find().sort(bew BasicDBObject("_id", -1)).skip(2).limit(2);
выведет 2 элемента коллекции collection, пропустив 2, с сортировкой в обратном порядке. 

Quiz: Java Driver: Sort, Skip and Limit

Supposed you had the following documents in a collection named things.
{ "_id" : 0, "value" : 10 }
{ "_id" : 1, "value" : 5 }
{ "_id" : 2, "value" : 7 }
{ "_id" : 3, "value" : 20 }
If you performed the following query in the Java driver:
collection.find().sort(new BasicDBObject("value", -1)).skip(2).limit(1);
which document would be returned?
Обновление документов:
Для обновления документов используют функцию update:
collection.update(new BasicDBObject("_id","alice"),new BasicDBObject("age",24));
Но если повторить обновление и добавить, например new BasicDBObject("coffee",1), то первоначальное обновление потеряется, чтобы этого не произошло пишем:
 collection.update(new BasicDBObject("_id","alice"),new BasicDBObject("$set", new BasicDBObject("gender","F")));
Синтаксис update():
update(obj1,obj2,upsert,multi), где
obj1 - объект, который будет обновляться,
obj2 - критерии для обновления, 
upsert(true/false) - создает объект, если не создан с каким либо параметром, 
multi(true/false) - обновление нескольких документов.

Удаление документов:
Для удаления всех документов можно написать:
collection.remove();
Если нам нужно удалить конкретный элемент, пишем:
collection.remove(new BasicDBObject("_id","alice"));

Quiz: Java Driver: Update and Remove

In the following code fragment, what is the Java expression in place of xxxx that will set the field "examiner" to the value "Jones" for the document with _id of 1. Please use the $set operator.
        # update using $set
        scores.update(new BasicDBObject("_id", 1), xxxx);
new BasicDBObject("$set", new BasicDBObject("examiner", "Jones"))













Комментариев нет:

Отправить комментарий