使用 MongoTemplate 插入数据时 手动指定集合名称时,索引不会自动创建 public void save(DatapointData data) { mongoTemplate.insert(data, data.getPid()); } public Collection insert(Collection batchToSave, String collectionName) { Assert.notNull(batchToSave, "BatchToSave must not be null!"); Assert.notNull(collectionName, "CollectionName must not be null!"); return this.doInsertBatch(collectionName, batchToSave, this.mongoConverter); } package com.chico.client.iot.entity; import java.io.Serializable; import lombok.Data; import org.springframework.data.mongodb.core.index.IndexDirection; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; /** * 数据点数据上报表 * */ @Data @Document(collection = "datapoint_data") public class DatapointData implements Serializable { private static final long serialVersionUID = 1765700798800606339L; /** * 设备id */ @Indexed private String devId; /** * 产品id */ private String pid; /** * 功能点的code */ @Indexed private String identifier; /** * 功能点的值 */ private String value; /** * 时间 */ @Indexed(direction = IndexDirection.DESCENDING) private Long time; } @Document(collection = "datapoint_data") 注解中这个集合能够正常创建。 但是mongodb中存的是物联网数据,集合名是使用的pid,方便管理 有没有方法能让mongodb 自动创建索引 补充:如下方法是能创建索引的,但是不太想用这种方式 mongoTemplate.indexOps(pid).ensureIndex(new Index().on("time", Sort.Direction.DESC));