Рассмотрим простой пример приложения, которое обращается к Mongo. Содержимое оставим из предыдущих частей.
В зависимостях будет лишь драйвер для Mongo:
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.5.0</version>
</dependency>
</dependencies>
Необходимо заметить, что я использую драйвер 3.х.х. В долшинстве примеров, что я нашел, использовался драйвер версии 2.х.х, в 3 версии большинство используемых в примерах объектов отмечены ка устаревшие (Deprecated).
Для начала посчитаем количество записей в коллекции и выведем ее:
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongo.getDatabase("test");
FindIterable<Document> unicorns = database.getCollection("employees").find();
long employeesCount = database.getCollection("employees").count();
System.out.println("count = " + employeesCount);
printD(id);
Функция для вывода коллекции:
private static void printD(Iterable<Document> objects){
objects.forEach(document -> document.forEach((key, value) -> System.out.println(key + " = " + value)));
}
Создадим новую запись: Document document = new Document();
document.put("name", "Martin");
document.put("hired", new Date());
document.put("skills", "[smart, responsible]");
document.put("age", 22);
document.put("gender", "m");
document.put("salary", 2468);
database.getCollection("employees").insertOne(document);
employeesCount = database.getCollection("employees").count();
System.out.println("count = " + employeesCount);
Количество записей увеличилось на 1. Попробуем обновить, созданную запись: Document find = new Document();
find.put("name", "Martin");
FindIterable<Document> beforeUpdate = database.getCollection("employees").find(find);
printD(beforeUpdate);
System.out.println("update:");
Document update = new Document();
Document set = new Document();
update.put("salary", 2479);
set.put("$set", update);
database.getCollection("employees").updateMany(find, set);
FindIterable<Document> updated = database.getCollection("employees").find(find);
printD(updated);
Поиск записи по ИД. Внимание, я использую свой ИД, необходимо использовать именно ваш, сегенерированный ид: System.out.println("find by id");
Document findById = new Document();
findById.put("_id", new ObjectId("5a1525ea0f6ce550de6fc392"));
FindIterable<Document> id = database.getCollection("employees").find(findById);
printD(id);
Удалим созданный объект: database.getCollection("employees").deleteMany(find);
employeesCount = database.getCollection("employees").count();
System.out.println("count = " + employeesCount);
Количество записей уменьшилось на 1.Полностью код приведен ниже:
package com;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.Date;
public class Application {
public static void main(String[] args) {
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongo.getDatabase("test");
FindIterable<Document> unicorns = database.getCollection("employees").find();
long employeesCount = database.getCollection("employees").count();
System.out.println("count = " + employeesCount);
printD(unicorns);
Document document = new Document();
document.put("name", "Martin");
document.put("hired", new Date());
document.put("skills", "[smart, responsible]");
document.put("age", 22);
document.put("gender", "m");
document.put("salary", 2468);
database.getCollection("employees").insertOne(document);
employeesCount = database.getCollection("employees").count();
System.out.println("count = " + employeesCount);
Document find = new Document();
find.put("name", "Martin");
FindIterable<Document> beforeUpdate = database.getCollection("employees").find(find);
printD(beforeUpdate);
System.out.println("update:");
Document update = new Document();
Document set = new Document();
update.put("salary", 2479);
set.put("$set", update);
database.getCollection("employees").updateMany(find, set);
FindIterable<Document> updated = database.getCollection("employees").find(find);
printD(updated);
System.out.println("find by id");
Document findById = new Document();
findById.put("_id", new ObjectId("5a1525ea0f6ce550de6fc392"));
FindIterable<Document> id = database.getCollection("employees").find(findById);
printD(id);
database.getCollection("employees").deleteMany(find);
employeesCount = database.getCollection("employees").count();
System.out.println("count = " + employeesCount);
}
private static void printD(Iterable<Document> objects){
objects.forEach(document -> document.forEach((key, value) -> System.out.println(key + " = " + value)));
}
}











