-1

I have some entities like that:

{
  "id": 1,
  ... 
  "items": [
     {
        "name": "name_1",
        ...
     }
  ]
}

I need to upsert that document in MongoDB, that means:

  1. if there is no documents with id == 1, then save a new document
  2. if there is document with id == 1, then I need to add 'item' from given document to persisted.

It is neccessary to do this by atomic operation. I use SpringData and MongoTemplate and tried to use aggregate operations, but didn't manage to achieve expected behavior.

Maybe somenopne knows how to do it with Spring Data?

Noel
  • 10,152
  • 30
  • 45
  • 67

1 Answers1

0

Your query will look something like this.

db.coll.updateMany(
  {"id": 1},
  {$push: {
      "items": {"name": "d"}
  }},
  {upsert: true}
  );

In spring boot,

Query query = Query.query(Criteria.where("id").is(1));

Update update = new Update();
update.push("items", <item object>);

UpdateResult updateResult = mongoTemplate.upsert(query, update, <class on which update has to run>.class);
Noel
  • 10,152
  • 30
  • 45
  • 67