zxl
6 小时以前 3b0516a2959e25576e4f3fda697a3b025d06c8c9
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
//package com.ycl.config;
//
//import com.mongodb.client.ListIndexesIterable;
//import com.mongodb.client.MongoCollection;
//import org.bson.Document;
//import org.springframework.boot.context.event.ApplicationReadyEvent;
//import org.springframework.context.event.EventListener;
//import org.springframework.data.mongodb.core.MongoTemplate;
//import org.springframework.stereotype.Component;
//
//import java.util.concurrent.atomic.AtomicReference;
//
///**
// * @author:xp
// * @date:2024/8/2 13:54
// */
//@Component
//public class MongoInit {
//
//    /**
//     * springboot启动时创建mongo的索引
//     *
//     * @param testEvent
//     */
//    @EventListener(classes = {ApplicationReadyEvent.class})
//    public void createIndex(ApplicationReadyEvent testEvent) {
//        MongoTemplate mongo = testEvent.getApplicationContext().getBean(MongoTemplate.class);
//        MongoCollection<Document> coll = mongo.getCollection("aa");
//
//
//    }
//
//    /**
//     * 检查没有索引就创建
//     *
//     * @param mongo mongodb实例
//     * @param collectionName mongodb集合名称
//     */
//    private void exitAndCreate(MongoTemplate mongo, String collectionName) {
//        // 获取集合
//        MongoCollection<Document> collection = mongo.getCollection("yourCollectionName");
//
//        // 创建一个全文索引,这里索引所有字符串字段
//        Document createIndex = new Document("$**", "text");
//        // 设置语言
//        createIndex.append("default_language", "chinese");
//        ListIndexesIterable<Document> indexes = collection.listIndexes();
//        AtomicReference<Boolean> exit = new AtomicReference<>(Boolean.FALSE);
//        indexes.forEach(index -> {
//            if (createIndex.equals(index)) {
//                exit.set(Boolean.TRUE);
//            }
//        });
//        if (! exit.get()) {
//            collection.createIndex(createIndex);
//        }
//    }
//
//}