MongoDB---com.mongodb.client

1、概述

    1.1、MongoDB  对数据的操作  分为   Read Operations(查询操作)、Write Operations(增、删、改);

    1.2、MongoDB 提供 客户端 用 bulk 方式 执行 Write Operations(批量写操作);

    1.3、

1
BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests);

        bulkWrite()  参数要求 传入一个List集合中元素类型是WriteModel(批量写的基类),有以下几个子类:

              DeleteManyModelDeleteOneModelInsertOneModelReplaceOneModelUpdateManyModelUpdateOneModel...

        bulkWrite()  返回值  BulkWriteResult ,代表一个成功批量写操作结果(封装了 操作结果的状态信息);

2、实战

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.integration/spring-integration-mongodb -->
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mongodb</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.11.2</version>
        </dependency>
 
    </dependencies>

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.springmongo;
 
 
/**
 * @description:
 * @author: anpeiyong
 * @date: Created in 2020/1/14 15:41
 * @since:
 */
public class Person {
 
    private String _id;
 
    private Integer age;
 
    private String name;
 
    public Person(String _id,Integer age,String name){
        this._id=_id;
        this.age=age;
        this.name=name;
    }
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String get_id() {
        return _id;
    }
 
    public void set_id(String _id) {
        this._id = _id;
    }
 
 
 
    @Override
    public String toString() {
        return this.age+":"+this.name;
    }
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package com.springmongo;
 
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.*;
import org.bson.Document;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexInfo;
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 java.util.ArrayList;
import java.util.List;
 
/**
 * @description:
 * @author: anpeiyong
 * @date: Created in 2019/11/11 19:19
 * @since:
 */
public class SpringMongoTest {
 
    static MongoTemplate mongoTemplate;
    static MongoDbFactory mongoDbFactory;
    static MongoCollection<Document> collection;
 
    static {
        mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(), "test");
        mongoTemplate=new MongoTemplate(mongoDbFactory);
        collection=mongoTemplate.getCollection("p10");
    }
 
    public static void main(String[] args) {
 
 
        //+++++++++++++++mongoTemplate使用+++++++++++++++++++++
        testAddIndex();
        testAdd();
        testGet();
        testUpdate();
        testDelete();
 
 
        //com.mongo.client使用(MongoCollection使用)
        testMongoClientAdd();
        testMongoClientDelete();
        testMongoClientUpdate();
    }
 
    private static void testAddIndex() {
        //ensureIndex()   确保在该集合上存在该索引
        Index index=new Index();
        index.on("name", Sort.Direction.DESC);
        mongoTemplate.indexOps("p10").ensureIndex(index);
    }
 
    public static void testAdd(){
 
        Person p1=new Person("1",12,"jack");
        Person p2=new Person("2",12,"jack");
        Person p3=new Person("3",12,"jack");
 
        //批量操作API
        // BulkMode.UNORDERED:表示并行处理,遇到错误时能继续执行不影响其他操作;
        // BulkMode.ORDERED:表示顺序执行,遇到错误时会停止所有执行
        BulkOperations operations=mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED,"pplist");
 
        //单条数据操作
        //save  插入2条相同数据   不会出现  DuplicateKeyException
        mongoTemplate.save(p1,"p7");   mongoTemplate.save(p1,"p7");
 
        //insert  插入2条相同数据    会出现  DuplicateKeyException
        mongoTemplate.insert(p2,"p2");
        operations.insert(p1);
        operations.execute();
 
        //批量数据操作
        List<Person> personList=new ArrayList<>();
        personList.add(p2); personList.add(p3);
        mongoTemplate.insert(personList,"plist");
        operations.insert(personList);
        operations.execute();
 
    }
 
    public static void testGet(){
 
        //获取所有索引
        List<IndexInfo> indexList=mongoTemplate.indexOps("p10").getIndexInfo();
        System.out.println(indexList);
 
        //查找所有集合内容
        List<Person> personList=mongoTemplate.findAll(Person.class,"p10");
        System.out.println(personList);
 
        //复合条件查询
        Criteria criteria=new Criteria();
        criteria.orOperator(Criteria.where("age").is(12),Criteria.where("name").is("rose"));
        Query query1=new Query(criteria);
        List<Person> pp2List=mongoTemplate.find(query1,Person.class,"p10");
        System.out.println(pp2List);
 
        //分页查询
        Query query2=new Query();
        query2.skip(0).limit(1);
        List<Person> pp3List=mongoTemplate.find(query2,Person.class,"p10");
        System.out.println(pp3List);
 
        //模糊查询
        Query query3=new Query();
        query3.addCriteria(Criteria.where("name").regex("ja"));
        List<Person> pp4List=mongoTemplate.find(query3,Person.class,"p10");
        System.out.println(pp4List);
 
        //条件查询
        Query query=new Query();
        query.addCriteria(Criteria.where("name").is("jj"));
        List<Person> ppList=mongoTemplate.find(query,Person.class,"p10");
        System.out.println(ppList);
    }
 
    public static void testUpdate(){
 
        BulkOperations operations=mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED,"p1");
 
        //单个修改
        Query query=new Query(Criteria.where("_id").is("5e1d7442ebbc1a60259a61dd"));
        Update update=new Update();
        update.set("age",13);
        update.set("name","lan");
        //传统实现
        mongoTemplate.updateFirst(query,update,"p1");
        //BulkOperations实现
        operations.updateOne(query,update);
        operations.execute();
 
        //批量修改
        Query query1=new Query(Criteria.where("name").regex("ja"));
        Update update1=new Update();
        update1.set("age",16);
        update.set("name","rose");
        mongoTemplate.updateMulti(query1,update1,"p1");
         
    }
 
    public static void testDelete(){
        Query query=new Query(Criteria.where("_id").is("5e1d76e0eacc6d52f2b581cd"));
        mongoTemplate.remove(query,Person.class,"p1");
    }
 
    public static void testMongoClientAdd(){
        //批量新增
        Person person=new Person("5",22,"jj");
        List<WriteModel<Document>> writeModelList=new ArrayList<>();
        Document insertDocument=new Document();
        insertDocument.put("_id",person.get_id());
        insertDocument.put("age",person.getAge());
        insertDocument.put("name",person.getName());
        InsertOneModel<Document> insertOneModel=new InsertOneModel<>(insertDocument);
        writeModelList.add(insertOneModel);
        testAddIndex();
        collection.bulkWrite(writeModelList);
 
        Person person2=new Person("7",20,"jjkk");
        List<Document> documentList=new ArrayList<>();
        Document insertDocument2=new Document();
        insertDocument2.put("_id",person2.get_id());
        insertDocument2.put("age",person2.getAge());
        insertDocument2.put("name",person2.getName());
        documentList.add(insertDocument2);
        testAddIndex();
        collection.insertMany(documentList);
 
        //单条新增
        Person person1=new Person("6",21,"jjj");
        Document insertDocument1=new Document();
        insertDocument1.put("_id",person1.get_id());
        insertDocument1.put("age",person1.getAge());
        insertDocument1.put("name",person1.getName());
        testAddIndex();
        collection.insertOne(insertDocument1);
    }
 
    public static void testMongoClientDelete(){
        //批量删除
        Document deleteDocument=new Document("_id","6");
        List<WriteModel<Document>> writeModelList=new ArrayList<>();
        //DeleteOneModel  至多删除一条匹配条件的记录
        DeleteOneModel<Document> deleteOneModel=new DeleteOneModel<Document>(deleteDocument);
        writeModelList.add(deleteOneModel);
        //DeleteManyModel  删除匹配条件的多条数据
        DeleteManyModel<Document> deleteManyModel=new DeleteManyModel<Document>(deleteDocument);
        writeModelList.add(deleteManyModel);
        collection.bulkWrite(writeModelList);
 
        Document deleteDocument2=new Document("name","jj");
        collection.deleteMany(deleteDocument2);
 
        //单条删除
        Document deleteDocument1=new Document("_id","7");
        collection.deleteOne(deleteDocument1);
    }
 
    public static void testMongoClientUpdate(){
        //单个修改
        Document document=new Document("_id","5");
        //---要修改的内容
        Document updateContent=new Document("$set",new Document("name","sss"));
        //---第一个参数:修改的id、第二个参数:修改后内容
        collection.updateOne(document,updateContent);
 
 
       //批量修改
        List<WriteModel<Document>> writeModelList=new ArrayList<>();
        Document document1=new Document("_id","6");
        //---要修改的内容
        Document updateContent1=new Document("$set",new Document("name","ccc"));
        //---第一个参数:要修改的id、
        //---第二个参数:修改后的内容
        UpdateOneModel<Document> updateOneModel=new UpdateOneModel<Document>(document1,updateContent1);
        //---第一个参数:要修改的id、
        //---第二个参数:修改后的内容、
        //---第三个参数:可选、不填也会默认生成一个,upset值为false(如果未查到需要更新的内容,什么也不做);
                                                //upset为true(将新的Document插入数据库[查询Document 与 更新Document的结合])
        UpdateOneModel<Document> updateOneModel1=new UpdateOneModel<Document>(document1,updateContent1,new UpdateOptions().upsert(false));
        writeModelList.add(updateOneModel);
        collection.bulkWrite(writeModelList);
    }
 
}

  

  

    

posted on   anpeiyong  阅读(4158)  评论(0编辑  收藏  举报

编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示