mongodb添加字段和创建自增主键

2021/8/4 19:06:53

本文主要是介绍mongodb添加字段和创建自增主键,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

sql类型

--添加字段
db.library_category.update({},{$set:{code:""}},{multi:1})
--添加自增序列集合

db.getCollection("sequence").drop();
db.createCollection("sequence");

//添加字段中的集合
db.getCollection("sequence").insert([ {
_id: "code1",
seqId: 7
} ]);


--给添加的字段赋值
db.getCollection('library_category').find({"code":6}).forEach(
function(item){
db.getCollection('library_category').update({"_id":item._id},{$set: {"code":db.sequence.findAndModify({
query: {_id:"code1" },
update: {$inc:{seqId:1}},
new: true
}).seqId}})
}
)

 

java 代码

一.
创建自定义注解:

package com.orangecds.designmaterial.api.entity;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* @author xiyun.zhao
* @title: AutoIncKey
* @projectName design-material
* @description: 标识注解:标识主键ID需要自动增长
* @date 2021/8/317:45
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {

}

二.
创建自增主键实体类

package com.orangecds.designmaterial.api.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

/**
* @program: design-material
* @ClassName SeqInfo
* @description: 创建自增长序列
* @author: xiyun.zhao
* @create: 2021-08-03 17:41
**/
@ApiModel("序列的类")
@Data
@Document(collection = "sequence")
public class SeqInfo {
@ApiModelProperty("逻辑主键Id")
@Indexed
private String id;

@ApiModelProperty("序列值")
private Long seqId;

}


三.
创建自定义注解监听的类

package com.orangecds.designmaterial.seque.listener;

import com.orangecds.designmaterial.api.entity.AutoIncKey;
import com.orangecds.designmaterial.api.entity.SeqInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
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 org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
/**
* @description: 实现监听类
* @author xiyun.zhao
* @param:
* @return:
* @date: 2021/8/4 10:16
*/
@Component
public class SaveEventListener extends AbstractMongoEventListener<Object>{
private static final Logger logger= LoggerFactory.getLogger(SaveEventListener.class);

修改git 的用户名称:git config --global --replace-all user.name "xiyun.zhao"

@Autowired
private MongoTemplate mongo;

@Override
public void onBeforeConvert(BeforeConvertEvent<Object> event) {
final Object source = event.getSource();
if (source != null) {
ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);
// 如果字段添加了我们自定义的AutoIncKey注解
if (field.isAnnotationPresent(AutoIncKey.class)) {
// 设置自增ID
field.set(source, getNextId(source.getClass().getSimpleName()));
}
}
});
}

}

private Long getNextId(String id) {
Query query = new Query(Criteria.where("id").is(id));
Update update = new Update();
update.inc("seqId", 1);
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
SeqInfo seqInfo= mongo.findAndModify(query, update, options, SeqInfo.class);
return seqInfo.getSeqId();
}

}



这篇关于mongodb添加字段和创建自增主键的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程