Chèn tài liệu vào bộ sưu tập mongodb java

Chúng tôi sẽ tiếp tục với bộ sưu tập Người dùng để chèn dữ liệu mà chúng tôi đã tạo sau khi kết nối với cơ sở dữ liệu MongoDB. Hãy để chúng tôi xem xét các tình huống khác nhau để chèn dữ liệu vào bộ sưu tập của chúng tôi Người dùng


Chèn Tài liệu vào Bộ sưu tập với mặc định _id

Giả sử, chúng tôi muốn tạo một tài liệu trong bộ sưu tập Người dùng của mình với tên trường và mô tả, chúng tôi sẽ sử dụng đoạn mã sau

package com.mongo;

import com.mongodb.DB; 
import com.mongodb.MongoClient; 
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

public class MakeConnection { 
	public static void main(String[] args) {
		try { 
			// code to create the connection
			MongoClient mongoClient = new MongoClient("localhost", 27017); 
			// code to connect to the database
			DB db = mongoClient.getDB("DemoDB");

			// get the User collection from DB
			DBCollection userCollection = db.getCollection("User");
			BasicDBObject bO = new BasicDBObject();

			bO.put("name", "XYZ");
			bO.put("description", "Data insertion in MongoDB");

			// inserting data into collection
			userCollection.insert(bO);
		} 
		catch(Exception e) { 
			e.printStackTrace(); 
		} 
	}
}

Trong đoạn mã trên, chúng tôi đã sử dụng phương pháp getCollection() để lấy bộ sưu tập hiện có Người dùng. Sau đó, một đối tượng của BasicDBObject được tạo và tên trường và mô tả được đặt trong đối tượng với các giá trị. Có thể nhìn thấy đầu ra được tạo bằng công cụ MongoDB Compass

Data Insertion in MongoDB

Kết quả của việc thực thi đoạn mã trên, một mục mới có tên và mô tả được tạo với giá trị _id được tạo ngẫu nhiên


Chèn Tài liệu vào Bộ sưu tập với _id tùy chỉnh

Trong khi tạo tài liệu (chèn dữ liệu) vào bất kỳ bộ sưu tập nào, mongoDB cung cấp id duy nhất của riêng nó được gọi là _id. Nếu chúng tôi muốn cung cấp id tùy chỉnh của riêng mình, chúng tôi có thể cung cấp nó. Tham khảo đoạn mã dưới đây cho cùng

package com.mongo;

import com.mongodb.DB; 
import com.mongodb.MongoClient; 
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

public class MakeConnection { 
	public static void main(String[] args) {
		try { 
			// code to create the connection
			MongoClient mongoClient = new MongoClient("localhost", 27017); 
			// code to connect to the database
			DB db = mongoClient.getDB("DemoDB");

			// get the User collection from DB
			DBCollection userCollection = db.getCollection("User");
			BasicDBObject bO = new BasicDBObject();

			// adding custom _id
			bO.put("_id", "xyz123");
			bO.put("name", "XYZ");
			bO.put("description", "Data insertion in MongoDB");

			// inserting data into collection
			userCollection.insert(bO);
		} 
		catch(Exception e) { 
			e.printStackTrace(); 
		} 
	}
}

Khi chương trình trên được thực thi, một tài liệu mới được chèn vào bộ sưu tập với các giá trị được cung cấp cùng với giá trị được cung cấp cho trường _id

Thực hiện thao tác ghi để chèn tài liệu mới vào bộ sưu tập, cập nhật tài liệu hoặc tài liệu hiện có trong bộ sưu tập, thay thế tài liệu hiện có trong bộ sưu tập hoặc xóa tài liệu hoặc tài liệu hiện có khỏi bộ sưu tập

điều kiện tiên quyết

  • Ví dụ dưới đây yêu cầu một bộ sưu tập

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    7 trong cơ sở dữ liệu
    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    8. Để tạo và điền vào bộ sưu tập, hãy làm theo hướng dẫn trong github

  • Bao gồm các câu lệnh nhập sau

     import com.mongodb.*;
     import com.mongodb.MongoClient;
     import com.mongodb.client.MongoCollection;
     import com.mongodb.client.MongoDatabase;
     import com.mongodb.client.model.Filters;
     import static com.mongodb.client.model.Filters.*;
     import static com.mongodb.client.model.Updates.*;
     import com.mongodb.client.model.UpdateOptions;
     import com.mongodb.client.result.*;
     import org.bson.Document;
     import org.bson.types.ObjectId;
    
    
     import java.util.List;
     import java.util.Arrays;
     import java.util.ArrayList;
    

Kết nối với Triển khai MongoDB

Kết nối với triển khai MongoDB, khai báo và xác định một phiên bản

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
9

Ví dụ: bao gồm mã sau để kết nối với triển khai MongoDB độc lập đang chạy trên máy chủ cục bộ trên cổng

Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
0 và xác định
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
1 để tham chiếu cơ sở dữ liệu
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
8 và
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
3 để tham chiếu bộ sưu tập
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
7

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");

Để biết thêm thông tin về cách kết nối với MongoDB, hãy xem Kết nối với MongoDB

Chèn tài liệu mới

Để chèn một tài liệu vào bộ sưu tập, bạn có thể sử dụng phương thức của bộ sưu tập

Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);

Ghi chú

Nếu không có trường

Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 cấp cao nhất nào được chỉ định trong tài liệu, trình điều khiển Java sẽ tự động thêm trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 vào tài liệu được chèn

Chèn nhiều tài liệu

Để thêm nhiều tài liệu, bạn có thể sử dụng phương thức của bộ sưu tập, phương thức này lấy danh sách tài liệu để chèn

Ví dụ sau chèn hai tài liệu vào bộ sưu tập

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);

Ghi chú

Nếu không có trường

Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 cấp cao nhất nào được chỉ định trong tài liệu, trình điều khiển Java sẽ tự động thêm trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 vào tài liệu được chèn

Cập nhật tài liệu hiện có

Để cập nhật các tài liệu hiện có trong một bộ sưu tập, bạn có thể sử dụng các phương thức của bộ sưu tập

bộ lọc

Bạn có thể chuyển tài liệu bộ lọc vào các phương thức để chỉ định tài liệu nào sẽ cập nhật. Đặc tả tài liệu bộ lọc giống như đối với hoạt động đọc. Để tạo điều kiện thuận lợi cho việc tạo các đối tượng bộ lọc, trình điều khiển Java cung cấp trình trợ giúp

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);
3

Để chỉ định một bộ lọc trống (i. e. phù hợp với tất cả các tài liệu trong một bộ sưu tập), sử dụng một đối tượng

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);
4 trống

Cập nhật toán tử

Để thay đổi một trường trong tài liệu, MongoDB cung cấp các toán tử cập nhật. Để chỉ định sửa đổi cần thực hiện bằng toán tử cập nhật, hãy sử dụng tài liệu cập nhật

Để tạo điều kiện thuận lợi cho việc tạo các tài liệu cập nhật, trình điều khiển Java cung cấp lớp

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);
5

quan trọng

Trường

Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 là bất biến; . e. bạn không thể thay đổi giá trị của trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6

Cập nhật một tài liệu duy nhất

Phương pháp này cập nhật tối đa một tài liệu, ngay cả khi điều kiện bộ lọc khớp với nhiều tài liệu trong bộ sưu tập

Thao tác sau trên bộ sưu tập

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
7 cập nhật tài liệu có trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 bằng với
collection.updateOne(
                eq("_id", new ObjectId("57506d62f57802807471dd41")),
                combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
1

collection.updateOne(
                eq("_id", new ObjectId("57506d62f57802807471dd41")),
                combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));

Cụ thể, thao tác sử dụng

  • để đặt giá trị của trường

    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    3 thành
    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    4 và trường
    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    5 thành
    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    6, và

  • để sửa đổi trường

    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    8 thành ngày hiện tại. Nếu trường
    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    8 không tồn tại, người vận hành sẽ thêm trường này vào tài liệu

tiền boa

Trong một số trường hợp bạn có thể cần cập nhật nhiều trường trong tài liệu, việc thay thế tài liệu có thể hiệu quả hơn. Thấy

Cập nhật nhiều tài liệu

Phương pháp cập nhật tất cả các tài liệu phù hợp với điều kiện lọc

Thao tác sau trên bộ sưu tập

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
7 cập nhật tất cả các tài liệu có trường
collection.updateOne(
                eq("_id", new ObjectId("57506d62f57802807471dd41")),
                combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
3 bằng với
collection.updateMany(
              eq("stars", 2),
              combine(set("stars", 0), currentDate("lastModified")));
3

collection.updateMany(
              eq("stars", 2),
              combine(set("stars", 0), currentDate("lastModified")));

Cụ thể, thao tác sử dụng

  • để đặt giá trị của trường

    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    3 thành
    collection.updateMany(
                  eq("stars", 2),
                  combine(set("stars", 0), currentDate("lastModified")));
    
    6 và

  • để sửa đổi trường

    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    8 thành ngày hiện tại. Nếu trường
    collection.updateOne(
                    eq("_id", new ObjectId("57506d62f57802807471dd41")),
                    combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
    
    8 không tồn tại, người vận hành sẽ thêm trường này vào tài liệu

Tùy chọn cập nhật

Với phương pháp và, bạn có thể bao gồm một tài liệu

collection.updateOne(
                eq("_id", 1),
                combine(set("name", "Fresh Breads and Tulips"), currentDate("lastModified")),
                new UpdateOptions().upsert(true).bypassDocumentValidation(true));
2 để chỉ định tùy chọn hoặc tùy chọn

collection.updateOne(
                eq("_id", 1),
                combine(set("name", "Fresh Breads and Tulips"), currentDate("lastModified")),
                new UpdateOptions().upsert(true).bypassDocumentValidation(true));

Thay thế một tài liệu hiện có

Để thay thế một tài liệu hiện có trong một bộ sưu tập, bạn có thể sử dụng phương thức của bộ sưu tập

quan trọng

Trường

Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 là bất biến; . e. bạn không thể thay thế giá trị trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6

bộ lọc

Bạn có thể chuyển tài liệu bộ lọc sang phương thức để chỉ định tài liệu nào sẽ thay thế. Đặc tả tài liệu bộ lọc giống như đối với hoạt động đọc. Để tạo điều kiện thuận lợi cho việc tạo các đối tượng bộ lọc, trình điều khiển Java cung cấp trình trợ giúp

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);
3

Để chỉ định một bộ lọc trống (i. e. phù hợp với tất cả các tài liệu trong một bộ sưu tập), sử dụng một đối tượng

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);
4 trống

Phương pháp này thay thế nhiều nhất một tài liệu, ngay cả khi điều kiện lọc phù hợp với nhiều tài liệu trong bộ sưu tập

Thay thế một tài liệu

Để thay thế một tài liệu, hãy chuyển một tài liệu mới cho phương thức

quan trọng

Tài liệu thay thế có thể có các trường khác với tài liệu gốc. Trong tài liệu thay thế, bạn có thể bỏ qua trường

Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 vì trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 là bất biến;

Thao tác sau trên bộ sưu tập

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
7 thay thế tài liệu có trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 bằng
collection.updateOne(
                eq("_id", new ObjectId("57506d62f57802807471dd41")),
                combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
1

collection.replaceOne(
                eq("_id", new ObjectId("57506d62f57802807471dd41")),
                new Document("name", "Green Salads Buffet")
                        .append("contact", "TBD")
                        .append("categories", Arrays.asList("Salads", "Health Foods", "Buffet")));

Xem thêm

Tùy chọn cập nhật

Với , bạn có thể bao gồm một tài liệu

collection.updateOne(
                eq("_id", 1),
                combine(set("name", "Fresh Breads and Tulips"), currentDate("lastModified")),
                new UpdateOptions().upsert(true).bypassDocumentValidation(true));
2 để chỉ định tùy chọn hoặc tùy chọn

collection.replaceOne(
                eq("name", "Orange Patisserie and Gelateria"),
                new Document("stars", 5)
                        .append("contact", "TBD")
                        .append("categories", Arrays.asList("Cafe", "Pastries", "Ice Cream")),
                new UpdateOptions().upsert(true).bypassDocumentValidation(true));

Xóa tài liệu

Để xóa tài liệu trong một bộ sưu tập, bạn có thể sử dụng phương thức và

bộ lọc

Bạn có thể chuyển tài liệu bộ lọc vào các phương thức để chỉ định tài liệu nào cần xóa. Đặc tả tài liệu bộ lọc giống như đối với hoạt động đọc. Để tạo điều kiện thuận lợi cho việc tạo các đối tượng bộ lọc, trình điều khiển Java cung cấp trình trợ giúp

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);
3

Để chỉ định một bộ lọc trống (i. e. phù hợp với tất cả các tài liệu trong một bộ sưu tập), sử dụng một đối tượng

Document doc1 = new Document("name", "Amarcord Pizzeria")
               .append("contact", new Document("phone", "264-555-0193")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.88502, 40.749556)))
               .append("stars", 2)
               .append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));


Document doc2 = new Document("name", "Blue Coffee Bar")
               .append("contact", new Document("phone", "604-555-0102")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.97902, 40.8479556)))
               .append("stars", 5)
               .append("categories", Arrays.asList("Coffee", "Pastries"));

List documents = new ArrayList();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);
4 trống

Xóa một tài liệu

Phương pháp này xóa tối đa một tài liệu, ngay cả khi điều kiện lọc phù hợp với nhiều tài liệu trong bộ sưu tập

Thao tác sau trên bộ sưu tập

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
7 xóa một tài liệu có trường
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
6 bằng
collection.updateOne(
                eq("_id", new ObjectId("57506d62f57802807471dd41")),
                combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
1

collection.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")));

Xóa nhiều tài liệu

Phương pháp xóa tất cả các tài liệu phù hợp với điều kiện lọc

Thao tác sau trên bộ sưu tập

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
7 xóa tất cả các tài liệu có trường
collection.updateOne(
                eq("_id", new ObjectId("57506d62f57802807471dd41")),
                combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified")));
3 bằng
collection.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")));
4

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
0

Xem thêm Bỏ bộ sưu tập

Viết mối quan tâm

Mối quan tâm ghi mô tả mức độ xác nhận được yêu cầu từ MongoDB cho các thao tác ghi

Các ứng dụng có thể định cấu hình mối quan tâm ghi ở ba cấp độ

  • Trong một

    collection.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")));
    
    5

    • Thông qua
      collection.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")));
      
      6, như trong ví dụ sau
    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    1
    • Thông qua
      collection.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")));
      
      7, như trong ví dụ sau
    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    2
  • Trong một

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    9 thông qua phương thức của nó, như trong ví dụ sau

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    3
  • Trong một

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    00 thông qua phương thức của nó, như trong ví dụ sau

    MongoClient mongoClient = new MongoClient();
    MongoDatabase database = mongoClient.getDatabase("test");
    MongoCollection collection = database.getCollection("restaurants");
    
    4

Các trường hợp

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
9 và
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
00 là bất biến. Gọi
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
04 trên một phiên bản
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
9 hoặc
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
00 hiện có trả về một phiên bản mới và không ảnh hưởng đến phiên bản mà phương thức được gọi

Ví dụ: trong trường hợp sau đây, đối tượng

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
07 có đa số mối quan tâm ghi trong khi mối quan tâm ghi của
Document document = new Document("name", "Café Con Leche")
               .append("contact", new Document("phone", "228-555-0149")
                                       .append("email", "[email protected]")
                                       .append("location",Arrays.asList(-73.92502, 40.8279556)))
               .append("stars", 3)
               .append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));

collection.insertOne(document);
3 không bị ảnh hưởng

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
5

Bạn có thể xây dựng

collection.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")));
6,
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
9 hoặc
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection collection = database.getCollection("restaurants");
00 để bao gồm sự kết hợp của mối quan tâm viết, mối quan tâm đọc và sở thích đọc

Làm cách nào để chèn tài liệu vào MongoDB bằng Java?

Bạn có thể chèn một tài liệu vào bộ sưu tập bằng cách sử dụng phương thức insertOne() trên đối tượng MongoCollection . Để chèn một tài liệu, hãy xây dựng một đối tượng Tài liệu chứa các trường và giá trị mà bạn muốn lưu trữ.

Làm cách nào để chèn dữ liệu vào bộ sưu tập trong MongoDB?

Để chèn dữ liệu vào bộ sưu tập MongoDB, bạn cần sử dụng phương thức insert() hoặc save() của MongoDB .

Lệnh nào được sử dụng để chèn tài liệu vào bộ sưu tập MongoDB?

db. thu thập. insertOne() chèn một tài liệu vào một bộ sưu tập. Ví dụ sau chèn một tài liệu mới vào bộ sưu tập hàng tồn kho.

Làm cách nào để chèn tệp JSON vào MongoDB bằng Java?

Cách đơn giản nhất để nhập JSON vào MongoDB là chuyển nó thành “tổ chức. bson. Đối tượng tài liệu” trước . Lớp này đại diện cho một tài liệu MongoDB chung không có loại cụ thể.