MongoDB Basics: Getting Started with CRUD in JAVA

Introduction

MongoDB is a documentary representative in the NoSQL world, and CRUD is easy to implement. It is easy to summarize using the CRUD API in JAVA.

Driver library introduction

build.gradle


// https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
compileInclude group: 'org.mongodb', name: 'mongo-java-driver', version: '3.11.0'

Create

Insert image

image.png

JAVA insert sample

MongoDBTest.java


package mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import org.bson.Document;

public class MongoDBTest {

	public static void main(String[] args) {
		//Generate MongoDB clients
		MongoClient client = MongoClients.create("mongodb://localhost:27017");
		//Get a DB object
		MongoDatabase db = client.getDatabase("mydb");
		//Get a user collection
		MongoCollection<Document> users = db.getCollection("users");

		//Set user attributes
		Document user = new Document();
		user.append("lastName", "tanaka");
		user.append("firstName", "ichiro");
		user.append("gender", "male");

		//Insert into DB
		users.insertOne(user);

		//Close the client
		client.close();
	}
}

Collection image

image.png

Multiple inserts

List<Document> userList = new ArrayList<Document>();
		
Document user1 = new Document();
user1.append("lastName", "tanaka");
		
Document user2 = new Document();
user2.append("lastName", "yamada");
		
userList.add(user1);
userList.add(user2);
		
//Insert list into DB
users.insertMany(userList);

Read

Search image

image.png

Find One Get the first one with the feeling of db.collection.find (filter) .first (). If you want to search by _id, the first method is convenient.

MongoDBTest.java


package mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

import org.bson.Document;
import org.bson.types.ObjectId;

public class MongoDBTest {

	public static void main(String[] args) {
		//Generate MongoDB clients
		MongoClient client = MongoClients.create("mongodb://localhost:27017");
		//Get a DB object
		MongoDatabase db = client.getDatabase("mydb");
		//Get a user collection
		MongoCollection<Document> users = db.getCollection("users");

		// _Search by id
		Document user = users.find(Filters.eq("_id", new ObjectId("5d858b36c491de05900c4e32"))).first();
		if (user != null) {
			System.out.println("lastName:" + user.getString("lastName"));
		}

		//Close the client
		client.close();
	}
}

output:

lastName:tanaka

Find List It is possible to narrow down by passing the search condition to the parameter of the find method. Various methods are provided in the Filters class. image.png image.png

Search sample

//Search for multiple people by surname
MongoCursor<Document> cursor = users.find(Filters.or(Filters.in("lastName", "tanaka", "yamada"))).cursor();
while (cursor.hasNext()) {
    Document user = (Document) cursor.next();
    // do something
}

//It is also convenient to convert to a list instead of a Cursor.
// List<Document> documents = users.find(Filters.or(Filters.in("lastName", "tanaka", "yamada"))).into(new ArrayList<Document>());

Sort, skip, limit, etc.

Document sort = new Document();
sort.append("updateDate", -1);
MongoCursor<Document> cursor = users.find(Filters.in("lastName", "tanaka", "yamada")).sort(sort).skip(20).limit(10).cursor();

Update

Update image

image.png

Update One

Update one data with updateOne method

MongoDBTest.java


package mongodb;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import java.util.Date;

import org.bson.Document;
import org.bson.types.ObjectId;

public class MongoDBTest {

	public static void main(String[] args) {
		//Generate MongoDB clients
		MongoClient client = MongoClients.create("mongodb://localhost:27017");
		//Get a DB object
		MongoDatabase db = client.getDatabase("mydb");
		//Get a user collection
		MongoCollection<Document> users = db.getCollection("users");
		
		//Update conditions
		Document filter = new Document();
		filter.append("_id", new ObjectId("5d858b36c491de05900c4e32"));
		
		//Update data
		Document updateSet = new Document();
		updateSet.append("lastName", "Suzuki");
		updateSet.append("updateDate", new Date());
		
		//update object
		Document update = new Document();
		update.append("$set", updateSet);
		
		//update
		users.updateOne(filter , update);
		
		//Close the client
		client.close();
	}
}

Updated collection data

image.png

Update Many If you want to update the data that matches the conditions, use the updateMany method. image.png

Update Manual: https://docs.mongodb.com/manual/tutorial/update-documents/

Replace One If you want to completely replace the document instead of updating some data, use the replaceOne method.

image.png

//Update conditions
Document filter = new Document();
filter.append("_id", new ObjectId("5d858b36c491de05900c4e32"));
		
//Update data
Document update = new Document();
update.append("lastName", "Suzuki");
update.append("updateDate", new Date());
		
//Replacement
users.replaceOne(filter, update);

One point to note is that if you process the document searched in the DB as replacement data, an error will occur. bad example:

//Get data from DB
Document user = users.find(Filters.eq("_id", new ObjectId("5d858b36c491de05900c4e32"))).first();
user.append("memo", "new user");
		
//Replacement(Wrong_Since it is an id, an error will occur. the same_If it is id, there is no problem.)
users.replaceOne(Filters.eq("_id", new ObjectId("5d859c77b64c3286a4d29d90")), user);

If the _id is different, you can clear the error by deleting the user's _id field. If you have Version data, you may want to use the replaceOne method.

//Get data from DB
Document user = users.find(Filters.eq("_id", new ObjectId("5d858b36c491de05900c4e32"))).first();
user.append("memo", "new user");
user.remove("_id");

Delete

Deleted image

image.png

deleteOne users.deleteOne(Filters.eq("_id", new ObjectId("5d859c77b64c3286a4d29d90")));

deleteMany ʻUsers.deleteMany (Filters.eq ("lastName", "Suzuki")); `

Delete related methods

image.png

Manual: https://docs.mongodb.com/manual/ CRUD (image of the text): https://docs.mongodb.com/manual/crud/

that's all

Recommended Posts

MongoDB Basics: Getting Started with CRUD in JAVA
Settings for getting started with MongoDB in python
Getting Started with Python Basics of Python
Getting Started with Python for PHPer-Super Basics
Getting started with Android!
1.1 Getting Started with Python
Getting started with apache2
Getting Started with Golang 1
Getting Started with Python
Getting Started with Django 1
Getting Started with Optimization
Getting Started with Golang 3
Getting started with AWS IoT easily in Python
Getting Started with Numpy
Getting started with Spark
Getting Started with Python
Getting Started with Pydantic
Getting Started with Golang 4
Getting Started with Jython
Getting Started with Django 2
Translate Getting Started With TensorFlow
Getting Started with Tkinter 2: Buttons
Getting Started with Go Assembly
Getting Started with PKI with Golang ―― 4
Getting Started with Python Django (1)
Getting Started with Python Django (4)
Getting Started with Python Django (3)
Getting Started with Python Django (6)
Getting Started with Django with PyCharm
Python3 | Getting Started with numpy
Getting Started with Python Django (5)
Getting Started with Flask # 2: Displaying Data Frames in Style Sheets
Getting Started with Python responder v2
Getting Started with Git (1) History Storage
Getting started with Sphinx. Generate docstring with Sphinx
Getting Started with Python Web Applications
Getting Started with Python for PHPer-Classes
Getting Started with Sparse Matrix with scipy.sparse
Getting Started with Julia for Pythonista
Getting Started with Cisco Spark REST-API
Basics of touching MongoDB with MongoEngine
Getting started with USD on Windows
Getting Started with Python Genetic Algorithms
Getting started with Python 3.8 on Windows
Getting Started with Python for PHPer-Functions
Get started with Python in Blender
Getting Started with CPU Steal Time
Getting Started with Heroku-Viewing Hello World in Python Django with Raspberry PI 3
Getting Started with python3 # 1 Learn Basic Knowledge
Getting Started with Flask with Azure Web Apps
Getting Started with Python Web Scraping Practice
Getting Started with Python Web Scraping Practice
Getting started with Dynamo from Python boto
Get Started with TopCoder in Python (2020 Edition)
Getting Started with Lisp for Pythonista: Supplement
Getting Started with Heroku, Deploying Flask App
Getting Started with TDD with Cyber-dojo at MobPro
Getting started with Python with 100 knocks on language processing
Getting Started with Drawing with matplotlib: Writing Simple Functions
Getting started with Keras Sequential model Japanese translation
[Translation] Getting Started with Rust for Python Programmers