[英]How do I update a list using MongoDB and Spring's repository?
I have a document like below:我有一个像下面这样的文件:
{
myDocument:
{
_id: (Auto-generated)
someField: "Hello world",
targetField: ["Steve", "Bill"]
}
}
Also, I have a repository like this:另外,我有一个这样的存储库:
@Repository
public interface FooRepository extends MongoRepository<MyDocument, String> {
}
My question is : "How do I add a new data inside of targetField without finding it locally? Because if my list gets too big, I don't want to load it, but only insert something new inside of it."我的问题是:“如何在 targetField 中添加新数据而不在本地找到它?因为如果我的列表太大,我不想加载它,而只想在其中插入一些新数据。”
Thanks.谢谢。
$addToSet
db.collection.update({
_id: "1"
},
{
"$addToSet": {
targetField: {
$each: [
"Steve",
"Sam"
]
}
}
},
{
new: true
})
Using MongoTemplate
, Query
and Update
by spring data mongodb
使用MongoTemplate
,通过spring data mongodb
Query
和Update
Update.addToSet
Add items to a Set (non-duplicatable) Update.addToSet
将项目添加到集合(不可复制)Update.push
Append items to an Array (duplicatable) Update.push
将项目追加到数组(可复制)import org.springframework.data.mongodb.core.*;
@Autowired
MongoTemplate mongoTemplate;
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(idToUpdate));
Update update = new Update();
update.addToSet("targetField", "newValue");
mongoTemplate.updateFirst(query, update, "collectionName");
FindAndModifyOptions
要获取结果文档,请使用FindAndModifyOptions
FindAndModifyOptions options = FindAndModifyOptions.options()
.returnNew(true);
TargetClass result = mongoTemplate.findAndModify(query, update, options, TargetClass.class, "collectionName");
update.addToSet("targetField")
.each("value1", "value2");
update.push("targetField")
.each("value1", "value2");
position
删除position
项目update.pop("targetField", position);
value
按value
删除项目update.pull("targetField", "value");
update.pullAll("targetField", new Object[]{"value1", "value2"});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.