Manipulate MongoDB data in Java applications
1. Start MongoDB Shell
2. Switch to the admin database and use the root account
3. Open Eclipse, create a Java Project and name it MongoJava
File --> New --> Java Project
4. Create a new package under the MongoJava project, named mongo.
Right click on MongoJava --> New --> mongo
5. Create a new class under the mongo package with the class name mimalianjie
Right click on mongo --> New --> Class
6. Add the jar package that the project depends on, right-click MongoJava and select Import
7. Select File System in General and click Next
8. Select the folder where the driver for mongo to connect to java is stored, and check Create top-level folder
9. Select mongo-java-driver-3.2.2.jar in the imported folder, right-click and select Add to Build Path in Build Path.
10. Connect to the database: Write code to connect to the Mongodb database. We need to specify the database name. If the specified database does not exist, mongo will automatically create the database.
package mongo;
import java.util.ArrayList;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
public class mimalianjie {
public static void main(String[] args) {
try {
ServerAddress serverAddress = new ServerAddress("localhost",27017);
ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("root", "admin", "strongs".toCharArray());
ArrayList<MongoCredential> credentials = new
ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
System.out.println("Connect to database successfully");
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
11. Create a collection: Same as the above steps, create a new class under the mongo package, the class name is chuangjianjihe, write code, the function is to create the collection mycol under the test library (use createCollection() in the com.mongodb.client.MongoDatabase class to Create a collection)
package mongo;
import java.util.ArrayList;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
public class chuanjianjihe {
public static void main(String[] args) {
try {
ServerAddress serverAddress = new ServerAddress("localhost",27017);
ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","strongs".toCharArray());
ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
mongoDatabase.createCollection("mycol");
System.out.println("集合mycol创建成功");
}catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage());
}
}
}
12. Validation in mongodb
13. Get the collection: Create a new class under the mongo package, named huoqujihe, and write code to get the required collection (use the getCollection() method of the com.mongodb.client.MongoDatabase class to get a collection)
package mongo;
import java.util.ArrayList;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class huoqujihe {
public static void main(String[] args) {
try {
ServerAddress serverAddress = new ServerAddress("localhost",27017);
ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("root","admin","strongs".toCharArray());
ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合mycol选择成功");
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage());
}
}
}
14. Insert documents: Create a new class in the mongo package named charuwendang. Its function is to connect to the test library, select the mycol collection and insert documents into it. (Use the insertMany() method of the com.mongodb.client.MongoCollection class to insert a document)
package mongo;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class charuwendang {
public static void main (String[] args) {
try {
ServerAddress serverAddress = new ServerAddress("localhost",27017);
ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("root"
,"admin","strongs".toCharArray());
ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合mycol选择成功");
Document document = new Document("name", "zhangyudashuju").
append("description", "YXCX").
append("likes", 100).
append("location", "BJ");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);
System.out.println("文档插入成功");
}catch(Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
15. Query verification in mongodb
16. Retrieve documents: Create a new class in the mongo package, named jiansuosuoyouwendang, whose function is to retrieve all documents in the mycol collection under the test library (use the find() method in the com.mongodb.client.MongoCollection class to obtain the documents in the collection all documents)
package mongo;
import java.util.ArrayList;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class jiansuosuoyouwendang {
public static void main( String args[] ){
try{
ServerAddress serverAddress = new ServerAddress("localhost",27017);
ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("root"
,"admin", "strongs".toCharArray());
ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合mycol选择成功");
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
17. Update the document: Create a new class in the mongo package named gengxinwendang. Its function is to select the mycol collection under the test library and change likes=100 in the document to likes=200 (use updateMany in the com.mongodb.client.MongoCollection class () method to update documents in the collection)
package mongo;
import java.util.ArrayList;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class gengxinwendang {
public static void main( String args[] ){
try{
ServerAddress serverAddress = new ServerAddress("localhost",27017);
ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("root"
,"admin", "strongs".toCharArray());
ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合mycol选择成功");
collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
18. Query validation in mongodb
19. Delete documents: Create a new class in the mongo package named sanchuwendang. Its function is to select the mycol collection under the test library and delete all documents that meet the conditions (likes=200). (Use the findOne() method in the com.mongodb.DBCollection class to get the first document, then use the remove method to delete)
package mongo;
import java.util.ArrayList;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class shanchuwendang {
public static void main( String args[] ){
try{
ServerAddress serverAddress = new ServerAddress("localhost",27017);
ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
addrs.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("root"
,"admin", "strongs".toCharArray());
ArrayList<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
MongoClient mongoClient = new MongoClient(addrs,credentials);
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("Connect to database successfully");
MongoCollection<org.bson.Document> collection = mongoDatabase.getCollection("mycol");
System.out.println("集合mycol选择成功");
//删除符合条件的第一个文档
//collection.deleteOne(Filters.eq("likes", 200));
//删除所有符合条件的文档
collection.deleteMany (Filters.eq("likes", 200));
//检索查看结果
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
System.out.println(mongoCursor.next());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
20. Query validation in mongodb
The query result is empty, which proves that the document has been deleted.
At this point, the experiment is over!