Hướng dẫn mongodb query between dates - truy vấn mongodb giữa các ngày

Tôi đã chơi xung quanh việc lưu trữ các tweet bên trong MongoDB, mỗi đối tượng trông như thế này:

{
"_id" : ObjectId("4c02c58de500fe1be1000005"),
"contributors" : null,
"text" : "Hello world",
"user" : {
    "following" : null,
    "followers_count" : 5,
    "utc_offset" : null,
    "location" : "",
    "profile_text_color" : "000000",
    "friends_count" : 11,
    "profile_link_color" : "0000ff",
    "verified" : false,
    "protected" : false,
    "url" : null,
    "contributors_enabled" : false,
    "created_at" : "Sun May 30 18:47:06 +0000 2010",
    "geo_enabled" : false,
    "profile_sidebar_border_color" : "87bc44",
    "statuses_count" : 13,
    "favourites_count" : 0,
    "description" : "",
    "notifications" : null,
    "profile_background_tile" : false,
    "lang" : "en",
    "id" : 149978111,
    "time_zone" : null,
    "profile_sidebar_fill_color" : "e0ff92"
},
"geo" : null,
"coordinates" : null,
"in_reply_to_user_id" : 149183152,
"place" : null,
"created_at" : "Sun May 30 20:07:35 +0000 2010",
"source" : "web",
"in_reply_to_status_id" : {
    "floatApprox" : 15061797850
},
"truncated" : false,
"favorited" : false,
"id" : {
    "floatApprox" : 15061838001
}

Làm thế nào tôi có thể viết một truy vấn kiểm tra created_at và tìm tất cả các đối tượng trong khoảng từ 18:47 đến 19:00? Tôi có cần cập nhật tài liệu của mình để ngày được lưu trữ ở một định dạng cụ thể không?

Hướng dẫn này hướng dẫn bạn qua quá trình sử dụng Dữ liệu Spring MongoDB để xây dựng một ứng dụng lưu trữ dữ liệu và lấy nó từ MongoDB, một cơ sở dữ liệu dựa trên tài liệu.

Những gì bạn sẽ xây dựng

Bạn sẽ lưu trữ Customer pojos (các đối tượng Java cũ đơn giản) trong cơ sở dữ liệu MongoDB bằng cách sử dụng Dữ liệu Spring MongoDB.

Những gì bạn cần

  • Khoảng 15 phút

  • Một trình soạn thảo văn bản yêu thích hoặc IDE

  • JDK 1.8 trở lên

  • Gradle 4+ hoặc Maven 3.2+

  • Bạn cũng có thể nhập mã thẳng vào IDE của mình:

    • Bộ công cụ mùa xuân (STS)

    • Ý tưởng intellij

Bắt đầu với Spring Inititalizr

Bạn có thể sử dụng dự án được khởi tạo trước này và nhấp vào Tạo để tải xuống tệp ZIP. Dự án này được cấu hình để phù hợp với các ví dụ trong hướng dẫn này.

Để khởi tạo thủ công dự án:

  1. Điều hướng đến https://start.spring.io. Dịch vụ này kéo theo tất cả các phụ thuộc bạn cần cho một ứng dụng và thực hiện hầu hết các thiết lập cho bạn.

  2. Chọn Gradle hoặc Maven và ngôn ngữ bạn muốn sử dụng. Hướng dẫn này giả định rằng bạn đã chọn Java.

  3. Nhấp vào phụ thuộc và chọn Dữ liệu mùa xuân MongoDB.Dependencies and select Spring Data MongoDB.

  4. Nhấp vào Tạo.Generate.

  5. Tải xuống tệp zip kết quả, đây là kho lưu trữ của ứng dụng web được cấu hình với các lựa chọn của bạn.

Nếu IDE của bạn có tích hợp khởi tạo lò xo, bạn có thể hoàn thành quy trình này từ IDE của mình.

Bạn cũng có thể chia rẽ dự án từ GitHub và mở nó trong IDE hoặc trình soạn thảo khác của bạn.

Cài đặt và khởi chạy MongoDB

Với dự án của bạn được thiết lập, bạn có thể cài đặt và khởi chạy cơ sở dữ liệu MongoDB.

Nếu bạn sử dụng máy Mac với homebrew, bạn có thể chạy lệnh sau:

Với MacPorts, bạn có thể chạy lệnh sau:

Sau khi bạn cài đặt MongoDB, bạn có thể khởi chạy nó trong cửa sổ bảng điều khiển bằng cách chạy lệnh sau (cũng khởi động quy trình máy chủ):

Bạn sẽ thấy đầu ra tương tự như sau:

all output going to: /usr/local/var/log/mongodb/mongo.log

Xác định một thực thể đơn giản

MongoDB là một cửa hàng tài liệu NoQuery. Trong ví dụ này, bạn lưu trữ các đối tượng Customer. Danh sách sau đây hiển thị lớp khách hàng (trong

all output going to: /usr/local/var/log/mongodb/mongo.log
1):

package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}

Ở đây bạn có một lớp Customer với ba thuộc tính:

all output going to: /usr/local/var/log/mongodb/mongo.log
3,
all output going to: /usr/local/var/log/mongodb/mongo.log
4 và
all output going to: /usr/local/var/log/mongodb/mongo.log
5.
all output going to: /usr/local/var/log/mongodb/mongo.log
3 chủ yếu được sử dụng nội bộ bởi MongoDB. Bạn cũng có một hàm tạo duy nhất để điền vào các thực thể khi tạo một thể hiện mới.

Trong hướng dẫn này, các getters và setters điển hình đã bị bỏ lại cho sự ngắn gọn.

all output going to: /usr/local/var/log/mongodb/mongo.log
3 phù hợp với tên tiêu chuẩn cho ID MongoDB, do đó, nó không yêu cầu bất kỳ chú thích đặc biệt nào gắn thẻ nó cho Dữ liệu mùa xuân MongoDB.

Hai thuộc tính khác,

all output going to: /usr/local/var/log/mongodb/mongo.log
4 và
all output going to: /usr/local/var/log/mongodb/mongo.log
5, không được bảo vệ. Người ta cho rằng chúng được ánh xạ tới các trường có cùng tên với các thuộc tính.

Phương pháp

package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
0 tiện lợi in các chi tiết về một khách hàng.

MongoDB lưu trữ dữ liệu trong các bộ sưu tập. Dữ liệu mùa xuân MongoDB ánh xạ lớp Customer thành một bộ sưu tập có tên
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
2. Nếu bạn muốn thay đổi tên của bộ sưu tập, bạn có thể sử dụng chú thích Spring Data MongoDB từ
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
3 trên lớp.

Tạo các truy vấn đơn giản

Dữ liệu mùa xuân MongoDB tập trung vào việc lưu trữ dữ liệu trong MongoDB. Nó cũng kế thừa chức năng từ dự án Dữ liệu Spring, chẳng hạn như khả năng rút ra các truy vấn. Về cơ bản, bạn không cần phải học ngôn ngữ truy vấn của MongoDB. Bạn có thể viết một số phương thức và các truy vấn được viết cho bạn.

Để xem cách thức hoạt động của nó, hãy tạo một giao diện kho lưu trữ truy vấn các tài liệu Customer, như danh sách sau (trong

package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
5) cho thấy:

package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);

}

package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
6 mở rộng giao diện
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
7 và cắm vào loại giá trị và ID mà nó hoạt động tương ứng với: Customer
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
9, tương ứng. Giao diện này đi kèm với nhiều hoạt động, bao gồm các hoạt động CRUD tiêu chuẩn (tạo, đọc, cập nhật và xóa).

Bạn có thể xác định các truy vấn khác bằng cách khai báo chữ ký phương pháp của họ. Trong trường hợp này, thêm

package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);

}
0, về cơ bản tìm kiếm các tài liệu thuộc loại Customer và tìm các tài liệu khớp với
all output going to: /usr/local/var/log/mongodb/mongo.log
4.

Bạn cũng có

package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);

}
3, tìm thấy một danh sách những người theo họ.

Trong một ứng dụng Java điển hình, bạn viết một lớp thực hiện

package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
6 và tự tạo ra các truy vấn. Điều làm cho Spring Data MongoDB trở nên hữu ích là thực tế là bạn không cần phải tạo triển khai này. Dữ liệu mùa xuân MongoDB tạo ra nó một cách nhanh chóng khi bạn chạy ứng dụng.

Bây giờ bạn có thể kết nối ứng dụng này và xem nó trông như thế nào!

Tạo một lớp ứng dụng

Spring IniticizR tạo một lớp đơn giản cho ứng dụng. Danh sách sau đây cho thấy lớp khởi tạo được tạo cho ví dụ này (trong

package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);

}
5):

package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}

package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);

}
6 là một chú thích thuận tiện thêm tất cả những điều sau đây:

  • package com.example.accessingdatamongodb;
    
    import java.util.List;
    
    import org.springframework.data.mongodb.repository.MongoRepository;
    
    public interface CustomerRepository extends MongoRepository<Customer, String> {
    
      public Customer findByFirstName(String firstName);
      public List<Customer> findByLastName(String lastName);
    
    }
    7: Thẻ lớp là nguồn định nghĩa đậu cho bối cảnh ứng dụng.

  • package com.example.accessingdatamongodb;
    
    import java.util.List;
    
    import org.springframework.data.mongodb.repository.MongoRepository;
    
    public interface CustomerRepository extends MongoRepository<Customer, String> {
    
      public Customer findByFirstName(String firstName);
      public List<Customer> findByLastName(String lastName);
    
    }
    8: Nói với Spring Boot để bắt đầu thêm đậu dựa trên cài đặt đường dẫn lớp, các loại đậu khác và các cài đặt thuộc tính khác nhau. Ví dụ: nếu
    package com.example.accessingdatamongodb;
    
    import java.util.List;
    
    import org.springframework.data.mongodb.repository.MongoRepository;
    
    public interface CustomerRepository extends MongoRepository<Customer, String> {
    
      public Customer findByFirstName(String firstName);
      public List<Customer> findByLastName(String lastName);
    
    }
    9 nằm trên đường dẫn lớp, chú thích này đánh dấu ứng dụng dưới dạng ứng dụng web và kích hoạt các hành vi chính, chẳng hạn như thiết lập
    package com.example.accessingdatamongodb;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class AccessingDataMongodbApplication {
    
      public static void main(String[] args) {
        SpringApplication.run(AccessingDataMongodbApplication.class, args);
      }
    
    }
    0.

  • package com.example.accessingdatamongodb;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class AccessingDataMongodbApplication {
    
      public static void main(String[] args) {
        SpringApplication.run(AccessingDataMongodbApplication.class, args);
      }
    
    }
    1: Nói với Spring để tìm kiếm các thành phần, cấu hình và dịch vụ khác trong gói
    package com.example.accessingdatamongodb;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class AccessingDataMongodbApplication {
    
      public static void main(String[] args) {
        SpringApplication.run(AccessingDataMongodbApplication.class, args);
      }
    
    }
    2, cho phép nó tìm các bộ điều khiển.

Phương pháp

package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}
3 sử dụng phương thức Spring Boot từ
package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}
4 để khởi chạy một ứng dụng. Bạn có nhận thấy rằng không có một dòng XML nào không? Không có tệp
package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}
5. Ứng dụng web này là Java thuần túy 100% và bạn không phải đối phó với việc định cấu hình bất kỳ hệ thống ống nước hoặc cơ sở hạ tầng nào.

Spring Boot tự động xử lý các kho lưu trữ đó miễn là chúng được bao gồm trong cùng một gói (hoặc gói phụ) của lớp

package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);

}
6 của bạn. Để kiểm soát thêm quy trình đăng ký, bạn có thể sử dụng chú thích
package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}
7.

Theo mặc định,
package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}
7 quét gói hiện tại cho bất kỳ giao diện nào mở rộng một trong các giao diện kho lưu trữ dữ liệu Spring. Bạn có thể sử dụng
package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}
9 của nó để nói một cách an toàn Data Data MongoDB để quét một gói gốc khác theo loại nếu bố cục dự án của bạn có nhiều dự án và nó không tìm thấy kho lưu trữ của bạn.

Dữ liệu mùa xuân MongoDB sử dụng

package com.example.accessingdatamongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    repository.deleteAll();

    // save a couple of customers
    repository.save(new Customer("Alice", "Smith"));
    repository.save(new Customer("Bob", "Smith"));

    // fetch all customers
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : repository.findAll()) {
      System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer
    System.out.println("Customer found with findByFirstName('Alice'):");
    System.out.println("--------------------------------");
    System.out.println(repository.findByFirstName("Alice"));

    System.out.println("Customers found with findByLastName('Smith'):");
    System.out.println("--------------------------------");
    for (Customer customer : repository.findByLastName("Smith")) {
      System.out.println(customer);
    }

  }

}
0 để thực hiện các truy vấn đằng sau các phương thức
package com.example.accessingdatamongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    repository.deleteAll();

    // save a couple of customers
    repository.save(new Customer("Alice", "Smith"));
    repository.save(new Customer("Bob", "Smith"));

    // fetch all customers
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : repository.findAll()) {
      System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer
    System.out.println("Customer found with findByFirstName('Alice'):");
    System.out.println("--------------------------------");
    System.out.println(repository.findByFirstName("Alice"));

    System.out.println("Customers found with findByLastName('Smith'):");
    System.out.println("--------------------------------");
    for (Customer customer : repository.findByLastName("Smith")) {
      System.out.println(customer);
    }

  }

}
1 của bạn. Bạn có thể tự mình sử dụng mẫu cho các truy vấn phức tạp hơn, nhưng hướng dẫn này không bao gồm điều đó. (Xem Hướng dẫn tham khảo Data Data MongoDB)

Bây giờ bạn cần sửa đổi lớp đơn giản mà khởi tạo đã tạo cho bạn. Bạn cần thiết lập một số dữ liệu và sử dụng nó để tạo đầu ra. Danh sách sau đây cho thấy lớp

package com.example.accessingdatamongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    repository.deleteAll();

    // save a couple of customers
    repository.save(new Customer("Alice", "Smith"));
    repository.save(new Customer("Bob", "Smith"));

    // fetch all customers
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : repository.findAll()) {
      System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer
    System.out.println("Customer found with findByFirstName('Alice'):");
    System.out.println("--------------------------------");
    System.out.println(repository.findByFirstName("Alice"));

    System.out.println("Customers found with findByLastName('Smith'):");
    System.out.println("--------------------------------");
    for (Customer customer : repository.findByLastName("Smith")) {
      System.out.println(customer);
    }

  }

}
2 đã hoàn thành (trong
package com.example.accessingdatamongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

  public Customer findByFirstName(String firstName);
  public List<Customer> findByLastName(String lastName);

}
5):

package com.example.accessingdatamongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    repository.deleteAll();

    // save a couple of customers
    repository.save(new Customer("Alice", "Smith"));
    repository.save(new Customer("Bob", "Smith"));

    // fetch all customers
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : repository.findAll()) {
      System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer
    System.out.println("Customer found with findByFirstName('Alice'):");
    System.out.println("--------------------------------");
    System.out.println(repository.findByFirstName("Alice"));

    System.out.println("Customers found with findByLastName('Smith'):");
    System.out.println("--------------------------------");
    for (Customer customer : repository.findByLastName("Smith")) {
      System.out.println(customer);
    }

  }

}

package com.example.accessingdatamongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    repository.deleteAll();

    // save a couple of customers
    repository.save(new Customer("Alice", "Smith"));
    repository.save(new Customer("Bob", "Smith"));

    // fetch all customers
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : repository.findAll()) {
      System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer
    System.out.println("Customer found with findByFirstName('Alice'):");
    System.out.println("--------------------------------");
    System.out.println(repository.findByFirstName("Alice"));

    System.out.println("Customers found with findByLastName('Smith'):");
    System.out.println("--------------------------------");
    for (Customer customer : repository.findByLastName("Smith")) {
      System.out.println(customer);
    }

  }

}
2 bao gồm một phương thức
package com.example.accessingdatamongodb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication {

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

}
3 tự động một ví dụ là
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
6. Dữ liệu mùa xuân MongoDB tự động tạo ra một proxy và tiêm nó ở đó. Chúng tôi sử dụng
package com.example.accessingdatamongodb;

import org.springframework.data.annotation.Id;


public class Customer {

  @Id
  public String id;

  public String firstName;
  public String lastName;

  public Customer() {}

  public Customer(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  public String toString() {
    return String.format(
        "Customer[id=%s, firstName='%s', lastName='%s']",
        id, firstName, lastName);
  }

}
6 thông qua một vài bài kiểm tra. Đầu tiên, nó lưu một số ít các đối tượng Customer, chứng minh phương thức
package com.example.accessingdatamongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    repository.deleteAll();

    // save a couple of customers
    repository.save(new Customer("Alice", "Smith"));
    repository.save(new Customer("Bob", "Smith"));

    // fetch all customers
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : repository.findAll()) {
      System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer
    System.out.println("Customer found with findByFirstName('Alice'):");
    System.out.println("--------------------------------");
    System.out.println(repository.findByFirstName("Alice"));

    System.out.println("Customers found with findByLastName('Smith'):");
    System.out.println("--------------------------------");
    for (Customer customer : repository.findByLastName("Smith")) {
      System.out.println(customer);
    }

  }

}
9 và thiết lập một số dữ liệu để sử dụng. Tiếp theo, nó gọi
java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
0 để tìm nạp tất cả các đối tượng Customer từ cơ sở dữ liệu. Sau đó, nó gọi
java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
2 để lấy một Customer bằng tên của cô ấy. Cuối cùng, nó gọi
java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
4 để tìm tất cả khách hàng có họ là
java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
5.

Theo mặc định, Spring Boot cố gắng kết nối với một thể hiện được lưu trữ cục bộ của MongoDB. Đọc các tài liệu tham khảo để biết chi tiết về việc trỏ ứng dụng của bạn vào một ví dụ của MongoDB được lưu trữ ở nơi khác.

Xây dựng một cái lọ thực thi

Bạn có thể chạy ứng dụng từ dòng lệnh với Gradle hoặc Maven. Bạn cũng có thể xây dựng một tệp JAR thực thi duy nhất có chứa tất cả các phụ thuộc, lớp và tài nguyên cần thiết và chạy điều đó. Xây dựng một bình có thể thực thi giúp bạn dễ dàng vận chuyển, phiên bản và triển khai dịch vụ như một ứng dụng trong suốt vòng đời phát triển, trên các môi trường khác nhau, v.v.

Nếu bạn sử dụng Gradle, bạn có thể chạy ứng dụng bằng cách sử dụng

java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
6.Ngoài ra, bạn có thể xây dựng tệp JAR bằng cách sử dụng
java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
7 và sau đó chạy tệp JAR, như sau:

java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar

Nếu bạn sử dụng Maven, bạn có thể chạy ứng dụng bằng cách sử dụng

java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
8.Ngoài ra, bạn có thể xây dựng tệp JAR với
java -jar build/libs/gs-accessing-data-mongodb-0.1.0.jar
9 và sau đó chạy tệp JAR, như sau:

java -jar target/gs-accessing-data-mongodb-0.1.0.jar

Khi

package com.example.accessingdatamongodb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AccessingDataMongodbApplication implements CommandLineRunner {

  @Autowired
  private CustomerRepository repository;

  public static void main(String[] args) {
    SpringApplication.run(AccessingDataMongodbApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {

    repository.deleteAll();

    // save a couple of customers
    repository.save(new Customer("Alice", "Smith"));
    repository.save(new Customer("Bob", "Smith"));

    // fetch all customers
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : repository.findAll()) {
      System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer
    System.out.println("Customer found with findByFirstName('Alice'):");
    System.out.println("--------------------------------");
    System.out.println(repository.findByFirstName("Alice"));

    System.out.println("Customers found with findByLastName('Smith'):");
    System.out.println("--------------------------------");
    for (Customer customer : repository.findByLastName("Smith")) {
      System.out.println(customer);
    }

  }

}
2 thực hiện
java -jar target/gs-accessing-data-mongodb-0.1.0.jar
1, phương thức
java -jar target/gs-accessing-data-mongodb-0.1.0.jar
2 được tự động gọi khi khởi động lò xo bắt đầu.Bạn sẽ thấy một cái gì đó như sau (với đầu ra khác, chẳng hạn như truy vấn):

== Customers found with findAll():
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']

== Customer found with findByFirstName('Alice'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
== Customers found with findByLastName('Smith'):
Customer[id=51df1b0a3004cb49c50210f8, firstName='Alice', lastName='Smith']
Customer[id=51df1b0a3004cb49c50210f9, firstName='Bob', lastName='Smith']

Bản tóm tắt

Xin chúc mừng!Bạn thiết lập một máy chủ MongoDB và viết một ứng dụng đơn giản sử dụng Data Data MongoDB để lưu các đối tượng vào và tìm nạp chúng từ cơ sở dữ liệu, tất cả mà không cần viết triển khai kho lưu trữ cụ thể.

Xem thêm