I have a MongoDB structure like this:
record = { 'field': 'value',
'field2': 'value2',
'events' : [ { 'event1': 1 }, { 'event2' : 2 }]
}
I am using Spring Data MongoDB package to access this data. There will be mainly writes to the data, so I would like to use the native "$push" functionality to add "events" to the "record", but I can't seem to figure out how to do it with MongoRepository without fetching the entire record and then pushing it and saving it back?
When doing using MongoRepository, you never really have a concrete implementation. Spring handles everything based on annotations or the names of the methods themselves
UPDATE
Would the correct way to be to implement a custom method on the repository and then use MongoTemplate to do it manually?
Example:
FooRepository.java
public interface FooRepository extends
CrudRepository<Foo, ObjectId>,
AppointmentWarehouseRepositoryCustom {
}
FooRepositoryCustom.java
public interface AppointmentWarehouseRepositoryCustom {
public void pushMethod();
}
FooRepositoryImpl.java
public class FooRepositoryImpl implements
AppointmentWarehouseRepositoryCustom {
@Autowired
protected MongoTemplate mongoTemplate;
public void pushMethod() {
// Push methods here.
}
}
Yes, DataNucleus JPA allows it, as well as to many other databases.
MongoRepository extends the PagingAndSortingRepository and QueryByExampleExecutor interfaces that further extend the CrudRepository interface. MongoRepository provides all the necessary methods which help to create a CRUD application and it also supports the custom derived query methods.
For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents. For example, if a user requires all grades from all students, then the below query can be written: Students.
The @Id annotation tells the mapper which property you want to use for the MongoDB _id property and the @Indexed annotation tells the mapping framework to call ensureIndex on that property of your document, making searches faster.
Yes, you must implement a custom method on the repository and your push
method would be something like this :
public class FooRepositoryImpl implements
AppointmentWarehouseRepositoryCustom {
@Autowired
protected MongoTemplate mongoTemplate;
public void pushMethod(String objectId, Object... events) {
mongoTemplate.updateFirst(
Query.query(Criteria.where("id").is(objectId)),
new Update().pushAll("events", events), Foo.class);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With