mongdb的使用

1、docker安裝mongdb

一、從dockerHub官網獲取鏡像

  • docker pull mongo

二、這裏的--name 放在前面並映射端口

  • docker run --name some-mongo -p 27017:27017 -d mongo --auth

三、進入容器

  • docker exec -it 容器ID /bin/bash

四、進入容器內部,建立用戶,而後退出

mongo  
 
use admin
 
db.createUser({user:"root",pwd:"root",roles:[{role:'root',db:'admin'}]})   //建立用戶,此用戶建立成功,則後續操做都須要用戶認證
 
exit  
複製代碼

2、mongdb插入文檔

一、插入文檔

>db.user.insert({title: '人員信息', 
    description: '人員描述',
    by: '身份證獲取',
    url: 'http://www.fhero.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})
複製代碼

以上實例中 col 是咱們的集合名,若是該集合不在該數據庫中, MongoDB 會自動建立該集合並插入文檔mongodb

3、Morphia 框架的使用

一、加入依賴

<dependencies>
    <dependency>
        <groupId>xyz.morphia</groupId>
        <artifactId>morphia</artifactId>
        <version>1.4.0</version>
    </dependency>
</dependencies>
複製代碼

二、加載實體和

@Configuration
public Datastore morphiaConfig(){
    @Value("${host}")
    private String host;
    @Value("${port}")
    private String port
    @Value("${Database}")
    private String Database;
     final Morphia morphia = new Morphia();
        // tell morphia where to find your classes
        // can be called multiple times with different packages or classes
        morphia.mapPackage("xyz.morphia.example");

        // create the Datastore connecting to the database running on the default port on the local host
        final Datastore datastore = morphia.createDatastore(new MongoClient(host),port,Database);
        datastore.getDB().dropDatabase();
        datastore.ensureIndexes();
        return datastore;
}
複製代碼

三、實體

@Entity("employees")
@Indexes(@Index(value = "salary", fields = @Field("salary")))
class Employee {
    @Id
    private ObjectId id;
    private String name;
    private Integer age;
    @Reference
    private Employee manager;
    @Reference
    private List<Employee> directReports = new ArrayList<Employee>();
    @Property("wage")
    private Double salary;

    public Employee() {
    }

    public Employee(final String name, final Double salary) {
        this.name = name;
        this.salary = salary;
    }

    public List<Employee> getDirectReports() {
        return directReports;
    }

    public void setDirectReports(final List<Employee> directReports) {
        this.directReports = directReports;
    }

    public ObjectId getId() {
        return id;
    }

    public Employee getManager() {
        return manager;
    }

    public void setManager(final Employee manager) {
        this.manager = manager;
    }

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(final Double salary) {
        this.salary = salary;
    }
}
複製代碼

必須加無參構造器,否則會報錯docker

四、持久層

final Employee elmer = new Employee("Elmer Fudd", 50000.0);
        datastore.save(elmer);

        final Employee daffy = new Employee("Daffy Duck", 40000.0);
        datastore.save(daffy);

        final Employee pepe = new Employee("Pepé Le Pew", 25000.0);
        datastore.save(pepe);

        elmer.getDirectReports().add(daffy);
        elmer.getDirectReports().add(pepe);

        datastore.save(elmer);

        Query<Employee> query = datastore.find(Employee.class);
        final List<Employee> employees = query.asList();

        Assert.assertEquals(3, employees.size());

        List<Employee> underpaid = datastore.find(Employee.class)
                                            .filter("salary <=", 30000)
                                            .asList();
        Assert.assertEquals(1, underpaid.size());

        underpaid = datastore.find(Employee.class)
                             .field("salary").lessThanOrEq(30000)
                             .asList();
        Assert.assertEquals(1, underpaid.size());

        final Query<Employee> underPaidQuery = datastore.find(Employee.class)
                                                        .filter("salary <=", 30000);
        final UpdateOperations<Employee> updateOperations = datastore.createUpdateOperations(Employee.class)
                                                                     .inc("salary", 10000);

        final UpdateResults results = datastore.update(underPaidQuery, updateOperations);

        Assert.assertEquals(1, results.getUpdatedCount());

        final Query<Employee> overPaidQuery = datastore.find(Employee.class)
                                                       .filter("salary >", 100000);
        datastore.delete(overPaidQuery);
複製代碼

4、Morphia使用示例

一、插入文檔

@Resource
 private Datastore datastore;
 
 datastore.save(sendSmsModel);
複製代碼

二、查看已插入文檔

單個條件查詢:
Query<UserDTO> query = datastore.createQuery(UserDTO.class);
    return query.field(FIELD_TASK_ID).equal(taskId).asList();
    
    List<UserDTO> taskTraceList =  datastore.createQuery(UserDTO.class)
            .search(String.valueOf(taskId))
            .order("_id")
            .asList();
            
多個條件查詢:
 UserDTO userDTO=datastore.find(UserDTO.class).field("wstBusinessNo").equal(wstBusinessNo)
        .field("wstTaskTypeCd").equal(wstTaskTypeCd)
        .field("wstTaskStatusCd").equal(wstTaskStatusCd).get();
複製代碼

三、更新數據

UserDTO userDTO =datastore.find(UserDTO.class).field("wstBusinessNo").equal(wstBusinessNo)
        .field("wstTaskTypeCd").equal(wstTaskTypeCd)
        .field("wstTaskStatusCd").equal(wstTaskStatusCd)
        .get();
    UpdateOperations<UserDTO> updateOperations = datastore.createUpdateOperations(UserDTO.class).set("wstTaskStatusCd",newTaskStatusCd);
    UpdateResults results = datastore.update(userDTO,updateOperations);
    }
複製代碼

四、刪除數據

if(StringUtils.isNotBlank(userDTO.getCertNo())){
        datastore.delete(datastore.createQuery(UserDTO.class).field("userId").equal(userDTO.getUserId()));
      }

複製代碼
相關文章
相關標籤/搜索