Spring Data Mongo:如何在MongoTemplate的findAndModify中使用$each修饰符?
在MongoTemplate的findAndModify中使用$each修饰符的方法
我懂你这种找不到官方文档细节的 frustration 😅,其实Spring Data MongoDB的MongoTemplate完全支持在findAndModify里用$each修饰符,只是需要借助Update类的链式方法来实现,刚好匹配你要往answers数组批量添加新元素的场景,下面直接给你实操代码和解释:
核心实现思路
要批量往数组字段添加元素,我们需要用MongoDB的$push操作符配合$each修饰符,而Spring Data MongoDB的Update类已经封装了对应的方法,不用手动拼接BSON。
完整代码示例
假设你的实体类是Question(对应MongoDB中的集合),其中answers是存储数组的字段,newAnswers是你要添加的新元素数组:
import org.springframework.data.mongodb.core.MongoTemplate; 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.data.mongodb.core.query.FindAndModifyOptions; import java.util.Arrays; import java.util.List; // 注入MongoTemplate(通常通过@Autowired) private final MongoTemplate mongoTemplate; public Question addAnswersToDocument(String documentId, List<String> newAnswers) { // 1. 构建查询条件:这里以文档ID为例,你可以换成其他匹配条件 Query query = new Query(Criteria.where("_id").is(documentId)); // 2. 构建Update操作:push("answers")对应Mongo的$push,each(newAnswers)对应$each修饰符 Update update = new Update().push("answers").each(newAnswers); // 3. 设置选项:如果需要返回更新后的文档,开启returnNew(true) FindAndModifyOptions options = FindAndModifyOptions.options() .returnNew(true); // 默认返回更新前的文档,设为true返回更新后的 // 执行findAndModify return mongoTemplate.findAndModify(query, update, options, Question.class); }
关键细节说明
- 这段代码对应的MongoDB原生操作是:
db.question.findAndModify({ "_id": ObjectId("your-document-id") }, { "$push": { "answers": { "$each": ["new-answer-1", "new-answer-2"] } } }, { "new": true }) - 如果你的需求是避免添加重复元素,可以把
push换成addToSet:
对应的Mongo操作是Update update = new Update().addToSet("answers").each(newAnswers);$addToSet配合$each,会自动跳过数组中已存在的元素。 - 如果文档中原本没有
answers字段,$push会自动创建这个数组字段并添加元素。
内容的提问来源于stack exchange,提问作者Dachstein
相关产品推荐
相关产品推荐

