How to upsert MongoDB Document with DbRef using spring mongoTemplate

1.1k views Asked by At
@Document
class Entity1 {
  @Id
  String id
  @DbRef(lazy=true)
  Entity2 entity2;
  String test;
}

mongoTemplate.upsert(
  new Query(Criteria.where("entity2.$id").is(entity2Id),
  new Update().set("test", "newValue"),
  Entity1.class);

I got Found $id field without a $ref before it, which is invalid

My question is: how to do this upsert with DbRef.

1

There are 1 answers

0
Demwis On

Pass entity to where query, not id. Create and save Entity2 to DB, then use entity2 instance and change your code to: where("entity2").is(entity2)