Merge remote-tracking branch 'upstream/master'
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/application.properties
|
||||
@@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.6.2</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>fauna-blog</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>fauna-blog</name>
|
||||
<description>Blogging Service built with FaunaDB</description>
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.faunadb</groupId>
|
||||
<artifactId>faunadb-java</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.faunablog;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class FaunaBlogApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(FaunaBlogApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.faunablog;
|
||||
|
||||
import com.faunadb.client.FaunaClient;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
|
||||
@Configuration
|
||||
class FaunaConfiguration {
|
||||
@Value("https://db.${fauna.region}.fauna.com/")
|
||||
private String faunaUrl;
|
||||
|
||||
@Value("${fauna.secret}")
|
||||
private String faunaSecret;
|
||||
|
||||
@Bean
|
||||
FaunaClient getFaunaClient() throws MalformedURLException {
|
||||
return FaunaClient.builder()
|
||||
.withEndpoint(faunaUrl)
|
||||
.withSecret(faunaSecret)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.faunablog;
|
||||
|
||||
import com.baeldung.faunablog.users.FaunaUserDetailsService;
|
||||
import com.faunadb.client.FaunaClient;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true)
|
||||
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
private FaunaClient faunaClient;
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.csrf().disable();
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/**").permitAll()
|
||||
.and().httpBasic();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Override
|
||||
public UserDetailsService userDetailsService() {
|
||||
return new FaunaUserDetailsService(faunaClient);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.faunablog.posts;
|
||||
|
||||
public record Author(String username, String name) {}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.faunablog.posts;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record Post(String id, String title, String content, Author author, Instant created, Long version) {}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.faunablog.posts;
|
||||
|
||||
import com.faunadb.client.errors.NotFoundException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/posts")
|
||||
public class PostsController {
|
||||
@Autowired
|
||||
private PostsService postsService;
|
||||
|
||||
@GetMapping
|
||||
public List<Post> listPosts(@RequestParam(value = "author", required = false) String author) throws ExecutionException, InterruptedException {
|
||||
return author == null ? postsService.getAllPosts() : postsService.getAuthorPosts("graham");
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public Post getPost(@PathVariable("id") String id, @RequestParam(value = "before", required = false) Long before)
|
||||
throws ExecutionException, InterruptedException {
|
||||
return postsService.getPost(id, before);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public void createPost(@RequestBody UpdatedPost post) throws ExecutionException, InterruptedException {
|
||||
String name = SecurityContextHolder.getContext().getAuthentication().getName();
|
||||
postsService.createPost(name, post.title(), post.content());
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public void updatePost(@PathVariable("id") String id, @RequestBody UpdatedPost post)
|
||||
throws ExecutionException, InterruptedException {
|
||||
postsService.updatePost(id, post.title(), post.content());
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotFoundException.class)
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public void postNotFound() {}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.baeldung.faunablog.posts;
|
||||
|
||||
import com.faunadb.client.FaunaClient;
|
||||
import com.faunadb.client.types.Value;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static com.faunadb.client.query.Language.*;
|
||||
|
||||
@Component
|
||||
public class PostsService {
|
||||
@Autowired
|
||||
private FaunaClient faunaClient;
|
||||
|
||||
Post getPost(String id, Long before) throws ExecutionException, InterruptedException {
|
||||
var query = Get(Ref(Collection("posts"), id));
|
||||
if (before != null) {
|
||||
query = At(Value(before - 1), query);
|
||||
}
|
||||
|
||||
var postResult= faunaClient.query(
|
||||
Let(
|
||||
"post", query
|
||||
).in(
|
||||
Obj(
|
||||
"post", Var("post"),
|
||||
"author", Get(Select(Arr(Value("data"), Value("authorRef")), Var("post")))
|
||||
)
|
||||
)).get();
|
||||
|
||||
return parsePost(postResult);
|
||||
}
|
||||
|
||||
List<Post> getAllPosts() throws ExecutionException, InterruptedException {
|
||||
var postsResult = faunaClient.query(Map(
|
||||
Paginate(
|
||||
Join(
|
||||
Documents(Collection("posts")),
|
||||
Index("posts_sort_by_created_desc")
|
||||
)
|
||||
),
|
||||
Lambda(
|
||||
Arr(Value("extra"), Value("ref")),
|
||||
Obj(
|
||||
"post", Get(Var("ref")),
|
||||
"author", Get(Select(Arr(Value("data"), Value("authorRef")), Get(Var("ref"))))
|
||||
)
|
||||
)
|
||||
)).get();
|
||||
|
||||
var posts = postsResult.at("data").asCollectionOf(Value.class).get();
|
||||
return posts.stream().map(this::parsePost).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<Post> getAuthorPosts(String author) throws ExecutionException, InterruptedException {
|
||||
var postsResult = faunaClient.query(Map(
|
||||
Paginate(
|
||||
Join(
|
||||
Match(Index("posts_by_author"), Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author))))),
|
||||
Index("posts_sort_by_created_desc")
|
||||
)
|
||||
),
|
||||
Lambda(
|
||||
Arr(Value("extra"), Value("ref")),
|
||||
Obj(
|
||||
"post", Get(Var("ref")),
|
||||
"author", Get(Select(Arr(Value("data"), Value("authorRef")), Get(Var("ref"))))
|
||||
)
|
||||
)
|
||||
)).get();
|
||||
|
||||
var posts = postsResult.at("data").asCollectionOf(Value.class).get();
|
||||
return posts.stream().map(this::parsePost).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void createPost(String author, String title, String contents) throws ExecutionException, InterruptedException {
|
||||
faunaClient.query(
|
||||
Create(Collection("posts"),
|
||||
Obj(
|
||||
"data", Obj(
|
||||
"title", Value(title),
|
||||
"contents", Value(contents),
|
||||
"created", Now(),
|
||||
"authorRef", Select(Value("ref"), Get(Match(Index("users_by_username"), Value(author)))))
|
||||
)
|
||||
)
|
||||
).get();
|
||||
}
|
||||
|
||||
public void updatePost(String id, String title, String contents) throws ExecutionException, InterruptedException {
|
||||
faunaClient.query(
|
||||
Update(Ref(Collection("posts"), id),
|
||||
Obj(
|
||||
"data", Obj(
|
||||
"title", Value(title),
|
||||
"contents", Value(contents))
|
||||
)
|
||||
)
|
||||
).get();
|
||||
}
|
||||
|
||||
private Post parsePost(Value entry) {
|
||||
var author = entry.at("author");
|
||||
var post = entry.at("post");
|
||||
|
||||
return new Post(
|
||||
post.at("ref").to(Value.RefV.class).get().getId(),
|
||||
post.at("data", "title").to(String.class).get(),
|
||||
post.at("data", "contents").to(String.class).get(),
|
||||
new Author(
|
||||
author.at("data", "username").to(String.class).get(),
|
||||
author.at("data", "name").to(String.class).get()
|
||||
),
|
||||
post.at("data", "created").to(Instant.class).get(),
|
||||
post.at("ts").to(Long.class).get()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.faunablog.posts;
|
||||
|
||||
public record UpdatedPost(String title, String content) {}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.faunablog.users;
|
||||
|
||||
import com.faunadb.client.FaunaClient;
|
||||
import com.faunadb.client.types.Value;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
import static com.faunadb.client.query.Language.*;
|
||||
|
||||
public class FaunaUserDetailsService implements UserDetailsService {
|
||||
private FaunaClient faunaClient;
|
||||
|
||||
public FaunaUserDetailsService(FaunaClient faunaClient) {
|
||||
this.faunaClient = faunaClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
try {
|
||||
Value user = faunaClient.query(Map(
|
||||
Paginate(Match(Index("users_by_username"), Value(username))),
|
||||
Lambda(Value("user"), Get(Var("user")))))
|
||||
.get();
|
||||
|
||||
Value userData = user.at("data").at(0).orNull();
|
||||
if (userData == null) {
|
||||
throw new UsernameNotFoundException("User not found");
|
||||
}
|
||||
|
||||
return User.withDefaultPasswordEncoder()
|
||||
.username(userData.at("data", "username").to(String.class).orNull())
|
||||
.password(userData.at("data", "password").to(String.class).orNull())
|
||||
.roles("USER")
|
||||
.build();
|
||||
} catch (ExecutionException | InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,25 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>integration-lite-first</id>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<forkCount>1</forkCount>
|
||||
<reuseForks>true</reuseForks>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- Cassandra -->
|
||||
<cassandra-driver-core.version>3.1.2</cassandra-driver-core.version>
|
||||
|
||||
@@ -13,3 +13,4 @@ This module contains articles about MongoDB in Java.
|
||||
- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json)
|
||||
- [How to Check Field Existence in MongoDB?](https://www.baeldung.com/mongodb-check-field-exists)
|
||||
- [Get Last Inserted Document ID in MongoDB With Java Driver](https://www.baeldung.com/java-mongodb-last-inserted-id)
|
||||
- [Update Multiple Fields in a MongoDB Document](https://www.baeldung.com/mongodb-update-multiple-fields)
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.baeldung.mongo;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
public class CollectionExistence {
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
|
||||
private static String testCollectionName;
|
||||
private static String databaseName;
|
||||
|
||||
public static void setUp() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
}
|
||||
databaseName = "baeldung";
|
||||
testCollectionName = "student";
|
||||
}
|
||||
|
||||
public static void collectionExistsSolution() {
|
||||
|
||||
DB db = mongoClient.getDB(databaseName);
|
||||
|
||||
System.out.println("collectionName " + testCollectionName + db.collectionExists(testCollectionName));
|
||||
|
||||
}
|
||||
|
||||
public static void createCollectionSolution() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
|
||||
try {
|
||||
database.createCollection(testCollectionName);
|
||||
|
||||
} catch (Exception exception) {
|
||||
System.err.println("Collection already Exists");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void listCollectionNamesSolution() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
boolean collectionExists = database.listCollectionNames()
|
||||
.into(new ArrayList<String>())
|
||||
.contains(testCollectionName);
|
||||
|
||||
System.out.println("collectionExists:- " + collectionExists);
|
||||
|
||||
}
|
||||
|
||||
public static void countSolution() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
|
||||
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||
|
||||
System.out.println(collection.count());
|
||||
|
||||
}
|
||||
|
||||
public static void main(String args[]) {
|
||||
|
||||
//
|
||||
// Connect to cluster (default is localhost:27017)
|
||||
//
|
||||
setUp();
|
||||
|
||||
//
|
||||
// Check the db existence using DB class's method
|
||||
//
|
||||
collectionExistsSolution();
|
||||
|
||||
//
|
||||
// Check the db existence using the createCollection method of MongoDatabase class
|
||||
//
|
||||
createCollectionSolution();
|
||||
|
||||
//
|
||||
// Check the db existence using the listCollectionNames method of MongoDatabase class
|
||||
//
|
||||
listCollectionNamesSolution();
|
||||
|
||||
//
|
||||
// Check the db existence using the count method of MongoDatabase class
|
||||
//
|
||||
countSolution();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
+23
-23
@@ -10,35 +10,35 @@ import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
public class MultipleFieldsExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) {
|
||||
|
||||
//
|
||||
// Connect to cluster (default is localhost:27017)
|
||||
//
|
||||
//
|
||||
// Connect to cluster (default is localhost:27017)
|
||||
//
|
||||
|
||||
MongoClient mongoClient = new MongoClient("localhost", 27017);
|
||||
MongoDatabase database = mongoClient.getDatabase("baeldung");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
MongoClient mongoClient = new MongoClient("localhost", 27017);
|
||||
MongoDatabase database = mongoClient.getDatabase("baeldung");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
|
||||
//
|
||||
// Filter on the basis of employee_id
|
||||
//
|
||||
//
|
||||
// Filter on the basis of employee_id
|
||||
//
|
||||
|
||||
BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
|
||||
BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
|
||||
|
||||
//
|
||||
// Update the fields in Document
|
||||
//
|
||||
//
|
||||
// Update the fields in Document
|
||||
//
|
||||
|
||||
BasicDBObject updateFields = new BasicDBObject();
|
||||
updateFields.append("department_id", 3);
|
||||
updateFields.append("job", "Sales Manager");
|
||||
BasicDBObject setQuery = new BasicDBObject();
|
||||
setQuery.append("$set", updateFields);
|
||||
UpdateResult updateResult = collection.updateMany(searchQuery, setQuery);
|
||||
BasicDBObject updateFields = new BasicDBObject();
|
||||
updateFields.append("department_id", 3);
|
||||
updateFields.append("job", "Sales Manager");
|
||||
BasicDBObject setQuery = new BasicDBObject();
|
||||
setQuery.append("$set", updateFields);
|
||||
UpdateResult updateResult = collection.updateMany(searchQuery, setQuery);
|
||||
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.mongo.update;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import com.mongodb.client.model.FindOneAndReplaceOptions;
|
||||
import com.mongodb.client.model.FindOneAndUpdateOptions;
|
||||
import com.mongodb.client.model.ReturnDocument;
|
||||
import com.mongodb.client.model.Updates;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
public class UpdateFields {
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase database;
|
||||
private static MongoCollection<Document> collection;
|
||||
|
||||
public static void updateOne() {
|
||||
|
||||
UpdateResult updateResult = collection.updateOne(Filters.eq("student_name", "Paul Starc"), Updates.set("address", "Hostel 2"));
|
||||
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
}
|
||||
|
||||
public static void updateMany() {
|
||||
|
||||
UpdateResult updateResult = collection.updateMany(Filters.lt("age", 20), Updates.set("Review", true));
|
||||
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
|
||||
}
|
||||
|
||||
public static void replaceOne() {
|
||||
|
||||
Document replaceDocument = new Document();
|
||||
replaceDocument.append("student_id", 8764)
|
||||
.append("student_name", "Paul Starc")
|
||||
.append("address", "Hostel 3")
|
||||
.append("age", 18)
|
||||
.append("roll_no", 199406);
|
||||
|
||||
UpdateResult updateResult = collection.replaceOne(Filters.eq("student_id", 8764), replaceDocument);
|
||||
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
|
||||
}
|
||||
|
||||
public static void findOneAndReplace() {
|
||||
|
||||
Document replaceDocument = new Document();
|
||||
replaceDocument.append("student_id", 8764)
|
||||
.append("student_name", "Paul Starc")
|
||||
.append("address", "Hostel 4")
|
||||
.append("age", 18)
|
||||
.append("roll_no", 199406);
|
||||
Document sort = new Document("roll_no", 1);
|
||||
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||
.append("address", 1);
|
||||
Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
|
||||
.sort(sort)
|
||||
.projection(projection)
|
||||
.returnDocument(ReturnDocument.AFTER));
|
||||
|
||||
System.out.println("resultDocument:- " + resultDocument);
|
||||
|
||||
}
|
||||
|
||||
public static void findOneAndUpdate() {
|
||||
|
||||
Document sort = new Document("roll_no", 1);
|
||||
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||
.append("address", 1);
|
||||
Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
|
||||
.sort(sort)
|
||||
.projection(projection)
|
||||
.returnDocument(ReturnDocument.AFTER));
|
||||
|
||||
System.out.println("resultDocument:- " + resultDocument);
|
||||
}
|
||||
|
||||
public static void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
database = mongoClient.getDatabase("baeldung");
|
||||
collection = database.getCollection("student");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
//
|
||||
// Connect to cluster (default is localhost:27017)
|
||||
//
|
||||
setup();
|
||||
|
||||
//
|
||||
// Update a document using updateOne method
|
||||
//
|
||||
updateOne();
|
||||
|
||||
//
|
||||
// Update documents using updateMany method
|
||||
//
|
||||
updateMany();
|
||||
|
||||
//
|
||||
// replace a document using replaceOne method
|
||||
//
|
||||
replaceOne();
|
||||
|
||||
//
|
||||
// replace a document using findOneAndReplace method
|
||||
//
|
||||
findOneAndReplace();
|
||||
|
||||
//
|
||||
// Update a document using findOneAndUpdate method
|
||||
//
|
||||
findOneAndUpdate();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+15
-16
@@ -11,26 +11,25 @@ import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
public class UpdateMultipleFields {
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) {
|
||||
|
||||
//
|
||||
// Connect to cluster
|
||||
//
|
||||
//
|
||||
// Connect to cluster
|
||||
//
|
||||
|
||||
MongoClient mongoClient = new MongoClient("localhost", 27007);
|
||||
MongoDatabase database = mongoClient.getDatabase("baeldung");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
MongoClient mongoClient = new MongoClient("localhost", 27007);
|
||||
MongoDatabase database = mongoClient.getDatabase("baeldung");
|
||||
MongoCollection<Document> collection = database.getCollection("employee");
|
||||
|
||||
//
|
||||
// Update query
|
||||
//
|
||||
//
|
||||
// Update query
|
||||
//
|
||||
|
||||
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875),
|
||||
Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||
UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
||||
System.out.println("updateResult:- " + updateResult);
|
||||
System.out.println("updateResult:- " + updateResult.getModifiedCount());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.baeldung.mongo;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
public class CollectionExistenceLiveTest {
|
||||
|
||||
private MongoClient mongoClient;
|
||||
private String testCollectionName;
|
||||
private String databaseName;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
databaseName = "baeldung";
|
||||
testCollectionName = "student";
|
||||
|
||||
// Create a new collection if it doesn't exists.
|
||||
try {
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
database.createCollection(testCollectionName);
|
||||
|
||||
} catch (Exception exception) {
|
||||
|
||||
System.out.println("Collection already Exists");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCreateCollection_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
Boolean collectionStatus = false;
|
||||
Boolean expectedStatus = true;
|
||||
|
||||
try {
|
||||
database.createCollection(testCollectionName);
|
||||
|
||||
} catch (Exception exception) {
|
||||
collectionStatus = true;
|
||||
System.err.println("Collection already Exists");
|
||||
}
|
||||
|
||||
assertEquals(expectedStatus, collectionStatus);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCollectionExists_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||
|
||||
DB db = mongoClient.getDB(databaseName);
|
||||
Boolean collectionStatus = db.collectionExists(testCollectionName);
|
||||
|
||||
Boolean expectedStatus = true;
|
||||
assertEquals(expectedStatus, collectionStatus);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
boolean collectionExists = database.listCollectionNames()
|
||||
.into(new ArrayList<String>())
|
||||
.contains(testCollectionName);
|
||||
|
||||
Boolean expectedStatus = true;
|
||||
assertEquals(expectedStatus, collectionExists);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCount_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
|
||||
|
||||
MongoDatabase database = mongoClient.getDatabase(databaseName);
|
||||
|
||||
MongoCollection<Document> collection = database.getCollection(testCollectionName);
|
||||
Boolean collectionExists = collection.count() > 0 ? true : false;
|
||||
|
||||
Boolean expectedStatus = false;
|
||||
assertEquals(expectedStatus, collectionExists);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package com.baeldung.update;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import com.mongodb.client.model.FindOneAndReplaceOptions;
|
||||
import com.mongodb.client.model.FindOneAndUpdateOptions;
|
||||
import com.mongodb.client.model.ReturnDocument;
|
||||
import com.mongodb.client.model.Updates;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
public class UpdateFieldLiveTest {
|
||||
|
||||
private static MongoClient mongoClient;
|
||||
private static MongoDatabase db;
|
||||
private static MongoCollection<Document> collection;
|
||||
|
||||
@BeforeClass
|
||||
public static void setup() {
|
||||
if (mongoClient == null) {
|
||||
mongoClient = new MongoClient("localhost", 27017);
|
||||
db = mongoClient.getDatabase("baeldung");
|
||||
collection = db.getCollection("student");
|
||||
|
||||
collection.insertOne(Document.parse("{ \"student_id\": 8764,\"student_name\": \"Paul Starc\",\"address\": \"Hostel 1\",\"age\": 16,\"roll_no\":199406}"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateOne() {
|
||||
|
||||
UpdateResult updateResult = collection.updateOne(Filters.eq("student_name", "Paul Starc"), Updates.set("address", "Hostel 2"));
|
||||
|
||||
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||
.first();
|
||||
assertNotNull(studentDetail);
|
||||
assertFalse(studentDetail.isEmpty());
|
||||
|
||||
String address = studentDetail.getString("address");
|
||||
String expectedAdderess = "Hostel 2";
|
||||
|
||||
assertEquals(expectedAdderess, address);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateMany() {
|
||||
|
||||
UpdateResult updateResult = collection.updateMany(Filters.lt("age", 20), Updates.set("Review", true));
|
||||
|
||||
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||
.first();
|
||||
assertNotNull(studentDetail);
|
||||
assertFalse(studentDetail.isEmpty());
|
||||
|
||||
Boolean review = studentDetail.getBoolean("Review");
|
||||
Boolean expectedAdderess = true;
|
||||
|
||||
assertEquals(expectedAdderess, review);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void replaceOne() {
|
||||
|
||||
Document replaceDocument = new Document();
|
||||
replaceDocument.append("student_id", 8764)
|
||||
.append("student_name", "Paul Starc")
|
||||
.append("address", "Hostel 3")
|
||||
.append("age", 18)
|
||||
.append("roll_no", 199406);
|
||||
|
||||
UpdateResult updateResult = collection.replaceOne(Filters.eq("student_id", 8764), replaceDocument);
|
||||
|
||||
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||
.first();
|
||||
assertNotNull(studentDetail);
|
||||
assertFalse(studentDetail.isEmpty());
|
||||
|
||||
Integer age = studentDetail.getInteger("age");
|
||||
Integer expectedAge = 18;
|
||||
|
||||
assertEquals(expectedAge, age);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findOneAndReplace() {
|
||||
|
||||
Document replaceDocument = new Document();
|
||||
replaceDocument.append("student_id", 8764)
|
||||
.append("student_name", "Paul Starc")
|
||||
.append("address", "Hostel 4")
|
||||
.append("age", 18)
|
||||
.append("roll_no", 199406);
|
||||
Document sort = new Document("roll_no", 1);
|
||||
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||
.append("address", 1);
|
||||
Document resultDocument = collection.findOneAndReplace(Filters.eq("student_id", 8764), replaceDocument, new FindOneAndReplaceOptions().upsert(true)
|
||||
.sort(sort)
|
||||
.projection(projection)
|
||||
.returnDocument(ReturnDocument.AFTER));
|
||||
|
||||
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||
.first();
|
||||
assertNotNull(studentDetail);
|
||||
assertFalse(studentDetail.isEmpty());
|
||||
|
||||
Integer age = studentDetail.getInteger("age");
|
||||
Integer expectedAge = 18;
|
||||
|
||||
assertEquals(expectedAge, age);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findOneAndUpdate() {
|
||||
|
||||
Document sort = new Document("roll_no", 1);
|
||||
Document projection = new Document("_id", 0).append("student_id", 1)
|
||||
.append("address", 1);
|
||||
Document resultDocument = collection.findOneAndUpdate(Filters.eq("student_id", 8764), Updates.inc("roll_no", 5), new FindOneAndUpdateOptions().upsert(true)
|
||||
.sort(sort)
|
||||
.projection(projection)
|
||||
.returnDocument(ReturnDocument.AFTER));
|
||||
|
||||
Document studentDetail = collection.find(Filters.eq("student_name", "Paul Starc"))
|
||||
.first();
|
||||
assertNotNull(studentDetail);
|
||||
assertFalse(studentDetail.isEmpty());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+7
-9
@@ -2,8 +2,6 @@ package com.baeldung.update;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.junit.Before;
|
||||
@@ -15,7 +13,6 @@ import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
import com.mongodb.client.model.Filters;
|
||||
import com.mongodb.client.model.Updates;
|
||||
import com.mongodb.client.result.UpdateResult;
|
||||
|
||||
public class UpdateMultipleFieldsLiveTest {
|
||||
|
||||
@@ -30,8 +27,7 @@ public class UpdateMultipleFieldsLiveTest {
|
||||
db = mongoClient.getDatabase("baeldung");
|
||||
collection = db.getCollection("employee");
|
||||
|
||||
collection.insertOne(Document.parse(
|
||||
"{'employee_id':794875,'employee_name': 'David smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
|
||||
collection.insertOne(Document.parse("{'employee_id':794875,'employee_name': 'David Smith','job': 'Sales Representative','department_id': 2,'salary': 20000,'hire_date': NumberLong(\"1643969311817\")}"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +43,8 @@ public class UpdateMultipleFieldsLiveTest {
|
||||
|
||||
collection.updateMany(searchQuery, setQuery);
|
||||
|
||||
Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
|
||||
Document nameDoc = collection.find(Filters.eq("employee_id", 794875))
|
||||
.first();
|
||||
assertNotNull(nameDoc);
|
||||
assertFalse(nameDoc.isEmpty());
|
||||
|
||||
@@ -62,10 +59,10 @@ public class UpdateMultipleFieldsLiveTest {
|
||||
@Test
|
||||
public void updateMultipleFieldsUsingDocument() {
|
||||
|
||||
collection.updateMany(Filters.eq("employee_id", 794875),
|
||||
Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||
collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
|
||||
|
||||
Document nameDoc = collection.find(Filters.eq("employee_id", 794875)).first();
|
||||
Document nameDoc = collection.find(Filters.eq("employee_id", 794875))
|
||||
.first();
|
||||
assertNotNull(nameDoc);
|
||||
assertFalse(nameDoc.isEmpty());
|
||||
|
||||
@@ -78,3 +75,4 @@ public class UpdateMultipleFieldsLiveTest {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user