惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
The Exploit Database - CXSecurity.com
F
Fortinet All Blogs
U
Unit 42
F
Full Disclosure
雷峰网
雷峰网
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
罗磊的独立博客
D
DataBreaches.Net
C
Check Point Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
O
OpenAI News
C
CXSECURITY Database RSS Feed - CXSecurity.com
aimingoo的专栏
aimingoo的专栏
S
Security @ Cisco Blogs
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
SegmentFault 最新的问题
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Hacker News
The Hacker News
Webroot Blog
Webroot Blog
Security Latest
Security Latest
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
N
News | PayPal Newsroom
P
Proofpoint News Feed
B
Blog RSS Feed
MongoDB | Blog
MongoDB | Blog
C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
Google Online Security Blog
Google Online Security Blog
H
Help Net Security
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
M
MIT News - Artificial intelligence
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
MyScale Blog
MyScale Blog
腾讯CDC

博客园 - mabiao008

idea更新代码时Merge和Rebase区别 CC skill Mac下载免费软件遇到问题解决 CQRS 错误码code是int类型好还是String类型好 idea2025版本破解 pgsql切换当前会话的模式 文档启动脚本报错:-bash: ./app.sh: /bin/bash^M: bad interpreter: No such file or directory Milvus索引 pandoc使用 idea把unicode转为中文 idea 插件分享 java项目处理OFD文件 java项目无法读取resources目录下的文件 三种数据对象的区别 Linux环境aspose插件word转pdf中文乱码解决方案 java List报错Method threw ‘java.lang.UnsupportedOperationException‘ exception. 解决 java字段值为null,转json后不存在该字段对应的key 格式化json大文件 springboot项目启动报错Command line is too long. Shorten the command line via JAR manifest or via a classpath file and rerun. com.alibaba.excel.exception.ExcelGenerateException: Can not close IO linux的TCP端口问题 关于linux端口号 linux下生成pdf文件名遇到问题 把页面查询到的数据导出PDF文件(html中的在线表单下载为pdf文件)
java程序中增加mongodb的联合索引
mabiao008 · 2025-05-22 · via 博客园 - mabiao008

早期,增加mongo索引,我只了解这一种

@Indexed
private String docId;

 这种不是联合索引。当时不了解其它方式,只想到一个办法,在服务启动后,判断是否含XX联合索引,没的话创建

 1 @Component
 2 @Slf4j
 3 public class MongoInit implements ApplicationRunner {
 4     @Resource
 5     protected MongoOperations mongoOperations;
 6 
 7     @Override
 8     public void run(ApplicationArguments args) throws Exception {
 9         try {
10             checkCollectionName();
11             checkCollectionIndex();
12         } catch (Exception e) {
13             log.error("索引插入异常, e:{}", e);
14         }
15     }
16     
17     /**
18      * 检查集合是否存在,不存在则创建
19      */
20     private void checkCollectionName() {
21         String collectionNameLib = "doc_lib";
22         if (!mongoOperations.collectionExists(collectionNameLib)) {
23             mongoOperations.createCollection(collectionNameLib);
24         }
25     }
26   
27     private void checkCollectionIndex() {
28         addIndexForLib();
29     }
30     
31   public void addIndexForLib() {
32         try {
33             IndexOperations indexOps = mongoOperations.indexOps("doc_lib");
34             List<IndexInfo> indexInfo = indexOps.getIndexInfo();
35             List<String> indexNames = indexInfo.stream().map(IndexInfo::getName).collect(Collectors.toList());
36 
37             if (!indexNames.contains("tenantId_account_label_orgCode")) {
38                 Map<String, Object> map = new HashMap<>();
39                 map.put("tenantId", 1);
40                 map.put("created_by", 1);
41                 map.put("label", 1);
42                 map.put("orgCode", 1);
43                 indexOps.ensureIndex(new CompoundIndexDefinition(new Document(map)).background());
44                 indexSleep();
45             }
46         } catch (Exception e) {
47             log.error("lib索引插入异常, e:{}", e);
48         }
49     }
50 }
51   

再后来,我得知了更优雅的方式:

spring:
  data:
    mongodb:
      uri: xxxx
      database: xxx
      auto-index-creation: true
@Document(collection = "emb_data")
@CompoundIndexes({
        @CompoundIndex(name = "task_knowledge_manualMark", def = "{'taskId': 1, 'knowledgeId': 1, 'manualMark': 1}")
})
@Accessors(chain = true)
public class EmbData extends AbstractAuditingEntity {

这样做在项目启动后,就可以加入联合索引了,哪怕表已经创建了也是没问题的。

mongodb中已存在了这个联合索引