MongoDB的简单使用

1. 添加依赖

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.6.3</version>
        </dependency>

2.  测试代码-windows版本的mogoDB

package com.xxy.mongodb.api;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: xuxiaoyu
 * @Date: 2019/11/26 11:11
 * 文档:相当于关系数据库的一行数据
 * 集合:多个文档组成一个集合,相当于关系数据库的表
 * 数据库:多个集合组成在一起,就是数据库,一个MongoDB实例支持多个数据库
 */
public class MongoDemo {
    public static void main(String[] args) {
         //findAll();
        //findSearch();
        findGt1000();
       //insert();

    }

    /**
     * 带条件查询
     */
    public static void findSearch(){
        MongoClient client=new MongoClient("127.0.0.1");//创建连接
        MongoDatabase spitdb = client.getDatabase("spitdb");//打开数据库
        MongoCollection<Document> spit = spitdb.getCollection("spit");//获取集合
        BasicDBObject bson=new BasicDBObject("id","1");// 构建查询条件
        FindIterable<Document> documents = spit.find(bson);//查询记录获取结果集合
        for (Document document : documents) {
            System.out.println("内容:"+document.getString("content"));
            System.out.println("用户ID:"+document.getString("useriD"));
        }
        client.close();//关闭连接
    }

    /**
     * 查询所有的
     */
    public static void findAll(){
        MongoClient client=new MongoClient("127.0.0.1");//创建连接
        MongoDatabase spitdb = client.getDatabase("spitdb");//打开数据库
        MongoCollection<Document> spit = spitdb.getCollection("spit");//获取集合
        FindIterable<Document> documents = spit.find();//查询记录获取文档集合
        for (Document document : documents) {
            System.out.println("id:"+document.getObjectId("_id"));
            System.out.println("内容:"+document.getString("content"));
            System.out.println("用户ID:"+document.getString("useriD"));
        }
        client.close();//关闭连接
    }
    /**
     * 查询浏览量大于1000的记录
     */
    public static void findGt1000(){
        MongoClient client=new MongoClient("127.0.0.1");//创建连接
        MongoDatabase spitdb = client.getDatabase("spitdb");//打开数据库
        MongoCollection<Document> spit = spitdb.getCollection("spit");//获取集合
        BasicDBObject bson=new BasicDBObject("visits",new BasicDBObject("$gt",1000) );// 构建查询条件
        FindIterable<Document> documents = spit.find(bson);
        for (Document document : documents) {
            System.out.println("内容:"+document.getString("content"));
            System.out.println("用户ID:"+document.getString("userid"));
        }
    }

    /**
     * 插入数据
     */
    public static void insert(){
        MongoClient client = new MongoClient("127.0.0.1");
        MongoDatabase spitdb = client.getDatabase("spitdb");
        MongoCollection<Document> spit = spitdb.getCollection("spit");

        Map<String,Object> map=new HashMap();

        map.put("content","哈哈");
        map.put("id","2332");
        map.put("userid","99994");
        map.put("visits",1234);
        map.put("publishtime",new Date());
        Document document=new Document(map);
        spit.insertOne(document);//插入数据
        client.close();
        System.out.println("插入成功");
    }
}
View Code

3. SpringDateMongoDB的使用

    1.依赖_配置

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
 </dependency>

application.yml中的配置
spring:
  data:
    mongodb:
      host: 192.168.254.129
      database: students

   2. pojo

package com.xxy.mongodb.springdatemongodb.pojo;

import org.springframework.data.annotation.Id;

import java.io.Serializable;

/**
 * @Description: MongoDB
 * @Author: xuxiaoyu
 * @Date: 2019/11/26 14:24
 */
public class Student implements Serializable {
    @Id
    private String _id;
    private String name;
    private String age;
    private String address;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student{" +
                "_id='" + _id + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
View Code

  3. dao

package com.xxy.mongodb.springdatemongodb.dao;

import com.xxy.mongodb.springdatemongodb.pojo.Student;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * @Description:
 * @Author: xuxiaoyu
 * @Date: 2019/11/26 14:34
 */
public interface StudentDao extends MongoRepository<Student,String> {
}
View Code

  4. controller

package com.xxy.mongodb.springdatemongodb.MongoTest;

import com.xxy.mongodb.springdatemongodb.dao.StudentDao;
import com.xxy.mongodb.springdatemongodb.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description:
 * @Author: xuxiaoyu
 * @Date: 2019/11/26 14:36
 */
@RestController
@RequestMapping("/mongo")
public class test {
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping(value = "save",method = RequestMethod.POST)
    public String save(@RequestBody Student student){
        studentDao.save(student);
        return "success";
    }
    @RequestMapping(value = "findone",method = RequestMethod.GET)
    public String findOne(){
        List<Student> all = studentDao.findAll();
        System.out.println(all);
        return "success";
    }
    /**
     * 年龄加1
     */
    @RequestMapping(value = "/addage/{id}",method = RequestMethod.PUT)
    public String addAge(@PathVariable String id){
        //查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        //修改条件
        Update update = new Update();
        update.inc("age",1);
        //updateFirst   修改符合条件第一条记录
        //updateMulti  修改符合条件的所有
        //Upsert       修改符合条件时如果不存在则添加
        mongoTemplate.updateFirst(query,update,"students");
        return "success";
    }
}
View Code

 

posted @ 2019-11-26 15:15  这都没什么  阅读(224)  评论(0编辑  收藏  举报