MongoDB常用操作

使用API时,先引入maven依赖

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.11.1</version>
</dependency>

创建连接

//mongoClient连接
protected static MongoClient mongoClient;
 public synchronized static MongodbClient getInstance(String mongodbUrl) {
        if (null == mongoClient) {
            mongoClient = MongoClients.create(mongodbUrl);
            if(null != mongoClient){
                log.info("mongoClient init success!");
            }
            else{
                log.info("mongoClient init failed!");
            }
        }
        return mongodbClient;
    } 

在生产环境中常用properties文件存放String mongodbUrl:

    private MongoClient mongoClient = new MongoClient(PropertityUtils.getValue("mongoaddr"),Integer.valueOf(PropertityUtils.getValue("mongoport")));
    

直接通过mongodb的host和port来创建client:

 

1 MongoClient mongoClient = MongoClients.create("mongodb://host1:27017");
//client连接到一个 Replica Set:
2 MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017,host3:27017"); 3 MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet");

关闭连接:

1 public void close() {
2     if(null!=mongoClient){
3         mongoClient.close();
4         mongoClient=null;
5     }
6 }
 1 //创建Collection
 2 
 3  public void createCollection(String dataBaseName,String collectionName){
 4         getDatabase(dataBaseName).createCollection(collectionName);
 5     }
 6 //查询dataBaseName
 7 public MongoDatabase getDatabase(String dataBaseName){ return mongoClient.getDatabase(dataBaseName); }
 8 //查询Collection
 9 
10 public List<String> listCollectionNames(String dataBaseName){
11  List<String> stringList = new ArrayList<String>(); 
12 mongoClient.getDatabase(dataBaseName).listCollectionNames().forEach((Consumer<? super String>) t->{ stringList.add(t); });
13  return stringList; } 
14 
15 public MongoCollection<Document> getCollectionByName(String dataBaseName, String collectionName)
  { return getDatabase(dataBaseName).getCollection(collectionName); } 16
 
关于MongoDB 的查询操作
 1  2 
 3 
 4 //通过id(objectid)精确查询
 5 public FindIterable<Document>  findMongoDbDocById(String dataBaseName, String collectionName, String id){
 6     BasicDBObject searchDoc = new BasicDBObject().append("_id", id);
 7    return getCollectionByName(dataBaseName,collectionName).find(searchDoc);
 8 }
 9 //通过id(objectid)模糊查询
10 public FindIterable<Document>  findMongoDbDocByIdRegex(String dataBaseName, String collectionName, String id){
11     BasicDBObject searchDoc = new BasicDBObject().append("_id", new BasicDBObject("$regex",id));
12     return getCollectionByName(dataBaseName,collectionName).find(searchDoc);
13 }
14 //通过开始id和结束id 查询(根据objectId范围查询)
15 public FindIterable<Document>  findMongoDbDocById(String dataBaseName, String collectionName, String startId,String endId){
16     BasicDBObject searchDoc = new BasicDBObject().append("_id", new BasicDBObject("$gte", startId).append("$lte", endId));
17     return getCollectionByName(dataBaseName,collectionName).find(searchDoc);
18 }
19 public FindIterable<Document> findMongoDbDoc(String dataBaseName, String collectionName,BasicDBObject basicDBObject){
20     return getCollectionByName(dataBaseName,collectionName).find(basicDBObject);
21 }
22 //限制查询返回的条数
23 public FindIterable<Document> findMongoDbDoc(String dataBaseName, String collectionName,BasicDBObject basicDBObject,Integer limitNum){
24     return findMongoDbDoc(dataBaseName,collectionName,basicDBObject).limit(limitNum) ;
25 }
26 public FindIterable<Document>  findMongoDbDocById(String dataBaseName, String collectionName, String startId,String endId,Integer limitNum){
27     return findMongoDbDocById(dataBaseName,collectionName,startId,endId).limit(limitNum);
28 }
29  
30 /**
31  * 降序查询(排序)
32  * @param dataBaseName
33  * @param collectionName
34  * @param startId
35  * @param endId
36  * @param sortField  排序字段
37  * @return
38  */
39 public FindIterable<Document>  findMongoDbDocByIdDescSort(String dataBaseName, String collectionName, String startId,String endId,String sortField){
40   return findMongoDbDocById(dataBaseName,collectionName,startId,endId).sort(new Document().append(sortField, -1));
41 }
42 public FindIterable<Document>  findMongoDbDocByIdDescSort(String dataBaseName, String collectionName, String startId,String endId,String sortField,Integer limitNum){
43     return findMongoDbDocByIdDescSort(dataBaseName,collectionName,startId,endId,sortField).limit(limitNum);
44 }
45  
46 /**
47  * 降序查询(排序)
48  * @param dataBaseName
49  * @param collectionName
50  * @param startId
51  * @param endId
52  * @param sortField  排序字段
53  * @return
54  */
55 public FindIterable<Document>  findMongoDbDocByIdAscSort(String dataBaseName, String collectionName, String startId,String endId,String sortField){
56     return findMongoDbDocById(dataBaseName,collectionName,startId,endId).sort(new Document().append(sortField, 1));
57 }
58 public FindIterable<Document>  findMongoDbDocByIdAscSort(String dataBaseName, String collectionName, String startId,String endId,String sortField,Integer limitNum){
59     return findMongoDbDocByIdAscSort(dataBaseName,collectionName,startId,endId,sortField).limit(limitNum);
60 }

数据的插入

1 public void insertDoc(String dataBaseName, String collectionName, Document document){
2      getCollectionByName(dataBaseName,collectionName).insertOne(document);
3  }
4  //插入多条记录
5  public void insertDoc(String dataBaseName, String collectionName,List<? extends Document> listData){
6      getCollectionByName(dataBaseName,collectionName).insertMany(listData);
7  }

数据的更新

 1 //更新单条
 2 public void updateDoc(String dataBaseName, String collectionName, Bson var1, Bson var2){
 3     getCollectionByName(dataBaseName,collectionName).updateOne(var1,var2);
 4 }
 5 public void updateDoc(String dataBaseName, String collectionName, Bson var1, List<? extends Bson> list){
 6     getCollectionByName(dataBaseName,collectionName).updateOne(var1,list);
 7 }
 8 //批量更新
 9 public void updateDocs(String dataBaseName, String collectionName, Bson var1, Bson var2){
10     getCollectionByName(dataBaseName,collectionName).updateMany(var1,var2);
11 }
12 public void updateDocs(String dataBaseName, String collectionName, Bson var1, List<? extends Bson> list){
13     getCollectionByName(dataBaseName,collectionName).updateMany(var1,list);
14 }

数据的删除

 

1 //单条删除 
2   public DeleteResult deleteDoc(String dataBaseName, String collectionName, Bson var1){
3         return getCollectionByName(dataBaseName,collectionName).deleteOne(var1);
4     }
5 //批量删除 
6     public DeleteResult deleteDocs(String dataBaseName, String collectionName,Bson var1){
7        return getCollectionByName(dataBaseName,collectionName).deleteMany(var1);
8     }

数据的跟新

 

1 //单条删除 
2   public DeleteResult deleteDoc(String dataBaseName, String collectionName, Bson var1){
3         return getCollectionByName(dataBaseName,collectionName).deleteOne(var1);
4     }
5 //批量删除 
6     public DeleteResult deleteDocs(String dataBaseName, String collectionName,Bson var1){
7        return getCollectionByName(dataBaseName,collectionName).deleteMany(var1);
8     }

数据的替换

1 //存在就替换,不存在的话就插入
2 public UpdateResult replaceDoc(String dataBaseName, String collectionName, Bson var1, Document var2){
3      return getCollectionByName(dataBaseName,collectionName).replaceOne(var1,var2);
4  }

关于MongoDB 的bulkWrite操作 (批量写入)

1 public BulkWriteResult bulkWrite(String dataBaseName, String collectionName, List<? extends WriteModel<? extends Document>> listData){
2    return getCollectionByName(dataBaseName,collectionName).bulkWrite(listData);
3 }

 

 

 

 

 

 
posted @ 2020-11-25 15:58  shan_zhayidian  阅读(270)  评论(0编辑  收藏  举报