mongo判断某些字段上有没有索引,进行动态创建

IndexOptions:
 private boolean background;
    private boolean unique;
    private String name;
    private boolean sparse;
    private Long expireAfterSeconds;
    private Integer version;
    private Bson weights;
    private String defaultLanguage;
    private String languageOverride;
    private Integer textVersion;
    private Integer sphereVersion;
    private Integer bits;
    private Double min;
    private Double max;
    private Double bucketSize;
    private Bson storageEngine;
    private Bson partialFilterExpression;
    private Collation collation;
    private Bson wildcardProjection;
    private boolean hidden;

 

        IndexOperations animals = mongoTemplate.indexOps("animals");
        List<IndexInfo> indexInfo = animals.getIndexInfo();
        for (IndexInfo index:indexInfo){
            List<IndexField> indexFields = index.getIndexFields();
            //索引名称
            String name = index.getName();
            for (IndexField indexField : indexFields) {
                //有索引的字段
                String key = indexField.getKey();
                //索引所在的字段不为空,并且与我们想要的目标字段不相等
                if(Objects.isNull(key)&&key.equals("目标字段")){
                    //在这里给目标字段设置索引 然后跳出循环即可
                    /**
                     *   IndexOptions indexOptions = new IndexOptions();
                     *                     //后台创建索引
                     *                     indexOptions.background(true);
                     *                     //唯一索引
                     * //                    indexOptions.unique(true);
                     *                     //如果为true,则索引仅引用具有指定字段的文档
                     * //                    indexOptions.sparse(true);
                     *                     mongoTemplate.createCollection("animals")
                     *                             .createIndex(Indexes.ascending("name"),
                     *                                     indexOptions);
                     */
                    break;
                }
            }
//            Optional<Document> collation = index.getCollation();

        }

 

如果某个字段不存在,就添加一个字段然后在建索引
 Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("phone").in("collect");
        query.addCriteria(criteria);
        Update update=new Update();
        update.set("like", "业余");
        mongoTemplate.upsert(query,  update, "animals");


这里使用like作为待新增的字段,然后调用上述,方法在进行给字段加索引

 运行中添加索引,这里是个唯一索引为实例

   Index index = new Index().on("field1", Sort.Direction.ASC).unique();
        mongoTemplate.indexOps("animals").ensureIndex(index);

 

posted @ 2023-08-26 15:50  余生请多指教ANT  阅读(196)  评论(0编辑  收藏  举报