MongoDb Java操作MongoDB之Mongodb-Driver

操作Mongodb主要有两种
1:java MongoDB驱动程操作Mongogodb(相当于JDBC)
2:spring-data-mongodb 中的mongodbTemplate

这节附上java MongoDB驱动程操作Mongogodb的一些代码操作:

pom文件如下:

<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<!--java-driver 操作Mongodb -->
 <dependency>
     <groupId>org.mongodb</groupId>
     <artifactId>mongodb-driver-sync</artifactId>
     <version>3.11.2</version>
 </dependency>
import com.mongodb.BasicDBObject;
import com.mongodb.client.*;
import com.mongodb.client.model.*;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.descending;
import static com.mongodb.client.model.Sorts.orderBy;

{ } 相当于一个Document 在MongoDB中,数据都是以文档的形式存在的,一个集合可以理解成一个“文档链”。文档对应的类是Document , 文档中间还可以内嵌文档

批量新增:

 @ApiOperation(value = "Mongogodb insert Document", notes = "Mongogodb insert Document")
    @RequestMapping(value = "/documentInsertMany", method = RequestMethod.POST)
    public List<Document> documentInsertMany(){
       MongoClient mongoClient = MongoClients.create();
       MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
       MongoCollection<Document> collection = database.getCollection("byuser");
       List<Document> list = new ArrayList<>(5);
       /*for (int i=0;i<20;i++){
           Document document = new Document();
           document.append("username", "whthomas").append("age", "23").
                   append("location", new Document("city", "beijing").append("x", "100").append("y", "200"));
           list.add(document);
       }*/
        for (int i=0;i<5;i++){
            Document document = new Document();
            document.append("userId", "1").append("sex", "男").
                    append("userName","LJ").append("age","20").append("length","10");
            list.add(document);
        }
       //insertMany
        collection.insertMany(list);
        mongoClient.close();
        return list;
    }

利用游标cursor便利Document:

 @ApiOperation(value = "Mongogodb find Document", notes = "Mongogodb find Document")
 @RequestMapping(value = "/findDocument", method = RequestMethod.GET)
    public List<Document> findDocument(){
        MongoClient mongoClient = MongoClients.create();
        MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
        MongoCollection<Document> collection = database.getCollection("sysuser");
        //first() 获取第一个文档
        //MongodbAggregate.mogo().find().first();
        MongoCursor<Document> cursor = collection.find().iterator();
        try {
          while (cursor.hasNext()){
              Document next = cursor.next();
              System.out.println(next.toJson());
          }
        }catch (Exception e){
        }finally {
            cursor.close();
        }
        return null;
    }

Mongogodb 精确条件查询:

 @ApiOperation(value = "Mongogodb 条件查询", notes = "Mongogodb 条件查询")
 @RequestMapping(value = "/findDocumentbywhy", method = RequestMethod.GET)
    public List<Document> findDocumentbywhy(){
        MongoClient mongoClient = MongoClients.create();
        MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
        MongoCollection<Document> collection = database.getCollection("sysuser");
        //first() 获取第一个文档
        //MongodbAggregate.mogo().find().first();
        // eq(),include(),excludeId(),orderBy(),descending()是静态方法
        MongoCursor<Document> iterator = collection.find(eq("username", "jin")).
                //excludeId(),include()不显示 _id
                projection(fields(include("username", "age"),excludeId())).
                // sort(orderBy(ascending("age"))对FindIterable对象使用sort函数进行排序。ascending函数表示升序,descending函数表示降序
                sort(orderBy(descending("age"))).
                iterator();
        while (iterator.hasNext()){
            Document next = iterator.next();
           /* 输出:{"username": "jin", "age": "30"}
                   {"username": "jin", "age": "29"}*/
            System.out.println(next.toJson());
        }
        iterator.close();
        return null;
    }

1:projection(),eq(),sort(),ascending(),orderBy()等导的都是静态方法
2:excludeId()不显示 _id

Mongogodb 模糊条件查询:
模糊匹配 username为ji且匹配是不区分大小写的

@ApiOperation(value = "Mongogodb BasicDBObject 模糊条件查询", notes = "Mongogodb BasicDBObject 条件查询")
@RequestMapping(value = "/findDocumentByBasicdbWhy", method = RequestMethod.GET)
    public List<Document> findDocumentByBasicdbWhy(){
        MongoClient mongoClient = MongoClients.create();
        MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
        MongoCollection<Document> collection = database.getCollection("sysuser");
        //构建查询条件
        BasicDBObject dbObject = new BasicDBObject();
        //精确查询
        dbObject.put("age","23");
        //模糊匹配
        // ("$options","i") 表示不区分大小写   m 个人理解这个参数是用来匹配value中有换行符(\n)的情形
        dbObject.put("username",new BasicDBObject("$regex","ji").append("$options","i"));
        //时间区间查询 记住如果想根据这种形式进行时间的区间查询 ,存储的时候 记得把字段存成字符串,就按yyyy-MM-dd HH:mm:ss 格式来
        //dbObject.put("times", new BasicDBObject("$gte", "2018-06-02 12:20:00").append("$lte","2018-07-04 10:02:46"));
        MongoCursor<Document> iterator = collection.find(dbObject).iterator();
        while (iterator.hasNext()){
            Document next = iterator.next();
            //输出:{"_id": {"$oid": "5e7c33bd5a83f51d7183aba5"}, "username": "jin", "age": "23", "location": {"city": "beijing", "x": "100", "y": "200"}}
            //{"_id": {"$oid": "5e7c7aa7fad8de09f44aaf61"}, "username": "jIn", "age": "23", "location": {"city": "beijing", "x": "100", "y": "200"}}
            System.out.println(next.toJson());
        }
        iterator.close();
        return null;
    }

1:$regex:表示匹配含有某个字符

2:append("$options",“i”)); 表示 i 不区分大小写

删除多条或一条:

//collection.deleteOne(eq("i", 110));
// DeleteResult deleteResult = collection.deleteMany(gte("i", 100));

Bulk CRUD操作(CRUD全在一个方法里面):

 @ApiOperation(value = "Bulk操作", notes = "Bulk操作")
 @RequestMapping(value = "/bulkwrite", method = RequestMethod.POST)
   public void bulkWrite(){
       MongoClient mongoClient = MongoClients.create();
       MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
       MongoCollection<Document> collection = database.getCollection("sysuser");
       collection.bulkWrite(Arrays.asList(
               new InsertOneModel<>(new Document("shuzi", 4)),
               new InsertOneModel<>(new Document("shuzi", 6)),
               //new Document("age", "99999") 代表修改哪一条
               // new Document("$set", new Document("age", "000")) 代表修改为啥样
               new UpdateOneModel<>(new Document("age", "99999"),
                       new Document("$set", new Document("age", "000"))),
               //删除
               new DeleteOneModel<>(new Document("age", "23")),
               //替换
               new ReplaceOneModel<>(new Document("x", "4"),
                       new Document("age", 101).append("x", 4))));
       mongoClient.close();
   }

Bulk批量删除操作:

@ApiOperation(value = "Bulk批量删除操作", notes = "Bulk批量删除操作")
@RequestMapping(value = "/bulkWriteDeleteMany", method = RequestMethod.POST)
  public void bulkWriteDeleteMany(){
       MongoClient mongoClient = MongoClients.create();
       MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
       MongoCollection<Document> collection = database.getCollection("sysuser");
      // new DeleteOneModel<>(new Document("age", "23"));
       collection.bulkWrite(Arrays.asList(
               //删除  一个new DeleteOneModel<>(new Document("age", "23")) 只能删一条 除非DeleteManyModel
               new DeleteManyModel<>(new Document("age", "23"))),
               //无序
               new BulkWriteOptions().ordered(false));
       mongoClient.close();
  }

(1)MongoDB提供了一种称为Bulk的操作方式,数据不会被立即被持久化到数据库中,而是等待程序调度,确定合适的时间持久化到数据库中。
(2)Bulk操作支持有序操作,和无序操作两种模式。有序操作中数据的的操作,会按照顺序操作,一旦发生错误,操作就会终止;而无序操作,则不安顺序执行,只会报告哪些操作发生了错误。
(3)Bulk操作支持增删改三种操作,对应的model分别是InsertOneModel、UpdateOneModel、DeleteOneModel、ReplaceOneModel。它们都继承于WriteModel
注意:
1:new BulkWriteOptions().ordered(false)放入bulkWrite()就是无序操作,没有就是有序
2:遇到参数一致的不能同时删除,修改!!!!!! 多条InsertManyOptions DeleteManyModel UpdateManyModel

Mongogodb Java Driver 的 Aggregates(管道)

(1)利用管道Aggregate的条件查询 group project

 @ApiOperation(value = "Mongogodb find Document", notes = "Mongogodb find Document")
 @RequestMapping(value = "/findJavaDriver2Document", method = RequestMethod.GET)
    public List<Document> findJavaDriver2Document(){
        MongoClient mongoClient = MongoClients.create();
        MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
        MongoCollection<Document> collection = database.getCollection("byuser");
        AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
                Aggregates.match(eq("userName", "连喜灯")),
                Aggregates.group("$age",Accumulators.sum("count",1)),
                //fields: excludeId() 不展示 _id  include() 展示username age
                Aggregates.project(fields(include("userName", "age","length"), excludeId())),
                //Aggregates.sort 等参数都是Bson
                Aggregates.sort(include("age")),
                Aggregates.limit(2)
        ));
        MongoCursor<Document> iterator = aggregate.iterator();
        while (iterator.hasNext()){
            Document document = iterator.next();
            //  Document 转实体类
            String realJson = document.toJson(JsonWriterSettings.builder().build());
            ByUser parse = JSON.parseObject(realJson, ByUser.class);
            /*输出:
            ByUser{userId='null', sex='null', userName='连喜灯', age='27', length=19}
            ByUser{userId='null', sex='null', userName='连喜灯', age='27', length=19}*/
            System.out.println(parse);
        }
        mongoClient.close();
        return null;
    }

(2)在(1)上增加Document转T
具体参考我的上一篇:https://blog.csdn.net/weixin_41987908/article/details/105177297

@ApiOperation(value = "Mongogodb find Document Group", notes = "Mongogodb find Document Group")
@RequestMapping(value = "/findJavaDriver2DocumentAndGroup", method = RequestMethod.GET)
    public List<Document> findJavaDriver2DocumentAndGroup(){
        MongoClient mongoClient = MongoClients.create();
        MongoDatabase database = mongoClient.getDatabase("richfit_mongodb");
        MongoCollection<Document> collection = database.getCollection("byuser");
        AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
                Aggregates.match(eq("userName", "连喜灯")),
                Aggregates.group("$age",Accumulators.sum("count",1)),
                Aggregates.project(fields(include("userName", "age","length"), excludeId()))
        ));
        MongoCursor<Document> iterator = aggregate.iterator();
        while (iterator.hasNext()){
            Document next = iterator.next();
            //  Document 转实体类
            String s = next.toJson(JsonWriterSettings.builder().build());
            ByUser byUser = JSON.parseObject(s, ByUser.class);
             /*输出:
            ByUser{userId='null', sex='null', userName='连喜灯', age='27', length=19}
            ByUser{userId='null', sex='null', userName='连喜灯', age='27', length=19}*/
            System.out.println(byUser.toString());
        }
        mongoClient.close();
        return null;
    }

project中有哪些字段就展示哪些字段 与 spring-data-mongodb 还不一样

实体类示例:

@Document(collection="byme")
 public class ByMe implements Serializable{

    private String userId;

    private String sex;

    private String userName;

    private String age;

 //新增后在数据库显示len,但是你返回用ByMe接收查询展示时还是展示length
    @Field("len")
    private int length;

    @Field("listadd")
    private List<Address> listAddress;

    public ByMe() {
    }

    public ByMe(String userId, String sex, String userName, String age, int length, List<Address> listAddress) {
        this.userId = userId;
        this.sex = sex;
        this.userName = userName;
        this.age = age;
        this.length = length;
        this.listAddress = listAddress;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAge() {
        return age;
    }

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

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public List<Address> getListAddress() {
        return listAddress;
    }

    public void setListAddress(List<Address> listAddress) {
        this.listAddress = listAddress;
    }

    @Override
    public String toString() {
        return "ByUser{" +
                "userId='" + userId + '\'' +
                ", sex='" + sex + '\'' +
                ", userName='" + userName + '\'' +
                ", age='" + age + '\'' +
                ", length=" + length +
                ", listAddress=" + listAddress +
                '}';
    }
发布了246 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41987908/article/details/105177619
今日推荐