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."
Thanks.
Using MongoTemplate
, Query
and Update
by spring data mongodb
Update.addToSet
Add items to a Set (non-duplicatable)Update.push
Append items to an Array (duplicatable)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 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
update.pop("targetField", position);
value
update.pull("targetField", "value");
update.pullAll("targetField", new Object[]{"value1", "value2"});