Home > Software engineering >  How do I update a list using MongoDB and Spring's repository?
How do I update a list using MongoDB and Spring's repository?

Time:11-12

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.

CodePudding user response:

$addToSet

db.collection.update({
  _id: "1"
},
{
  "$addToSet": {
    targetField: {
      $each: [
        "Steve",
        "Sam"
      ]
    }
  }
},
{
  new: true
})

mongoplayground

CodePudding user response:

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");
  • To get result document, using FindAndModifyOptions
FindAndModifyOptions options = FindAndModifyOptions.options()
        .returnNew(true);
TargetClass result = mongoTemplate.findAndModify(query, update, options, TargetClass.class, "collectionName");
  • Add multiple value
update.addToSet("targetField")
    .each("value1", "value2");
update.push("targetField")
    .each("value1", "value2");
  • Remove item at position
update.pop("targetField", position);
  • Remove item by value
update.pull("targetField", "value");
  • Remove multiple items
update.pullAll("targetField", new Object[]{"value1", "value2"});
  • Related