简体   繁体   中英

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."

Thanks.

$addToSet

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

mongoplayground

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"});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM