Reputation: 143
I am trying to use spring-data to replace our current usage of POJO to Document with mongodb, in this particular case instead of using a field as Id for the entity I use some fields.
For example, if I have this pojo:
class Thing {
public String firstName;
public String lastName;
public Int age;
}
At the moment to save it to mongodb I first do a conversion to Document:
Document doc = new Document();
doc.append("firstName", thing.firstName);
doc.append("lastName", thing.lastName);
doc.append("age", thing.age);
Then I create a query:
BasicDBObject query = new BasicDBObject(
and(
new BasicDBObject("firstName", thing.firstName),
new BasicDBObject("lastName", thing.lastName))
And then I upsert the doc using mongodb driver.
collection.updateOne(query, document, UpdateOptions().upsert(true))
This way I get the age
updated only and do not need to bother about the ObjectId that there is no meaning for me.
Now I want to change it to spring-data-mongodb to be less error prone when writing the document conversion part and be more productive. But I could not find how to do something similar with spring-data-mongodb, the save in MongoRepository api is base in the ObjectId and I can not find any annotation or bean to override/create to let me do something like this.
In a perfect world I would have something like a composite key for spring-data-mongodb. So for instance I would have to just write my POJO this way:
class Thing {
@Id public String firstName;
@Id public String lastName;
public Int age;
}
Or (not the better case but maybe acceptable)
class ThingKey {
public String firstName;
public String lastName;
}
class Thing {
@Id public ThingKey thingKey;
public Int age;
}
And the save would be able to figure out that this is a upsert to a existing entity and do act with this regards.
PS: The POJOs here are simplified versions to help understand the problem and are not the final version that I am using.
Upvotes: 2
Views: 4665
Reputation: 201028
There is a section on "upserting" in the official docs. It looks like you have to use either the upsert()
or findAndModify()
on MongoTemplate
.
Alternatively, you could just do a find()
, perform your changes to the object that is returned, and then do a save()
.
Upvotes: 2