Skip to main content

Commonly used methods of MongoOperations in Spring Data MongoDB

 Some commonly used methods of `MongoOperations` in Spring Data MongoDB, along with examples:

1. Insert Documents:
   - insert(Object objectToSave)`: Inserts a document into the collection.

    
YourEntity entity = new YourEntity("value1", "value2");
     mongoOperations.insert(entity);



2. Find Documents:
   - find(Query query, Class<T> entityClass)`: Finds documents matching the given query.

    
Query query = new Query(Criteria.where("field1").is("value1"));
     List<YourEntity> result = mongoOperations.find(query, YourEntity.class);



   - findOne(Query query, Class<T> entityClass)`: Finds the first document matching the query.

    
Query query = new Query(Criteria.where("field1").is("value1"));
     YourEntity entity = mongoOperations.findOne(query, YourEntity.class);

    

3. Update Documents:
   - updateFirst(Query query, Update update, Class<T> entityClass)`: Updates the first document matching the query.

    
Query query = new Query(Criteria.where("field1").is("value1"));
     Update update = new Update().set("field2", "new value");
     mongoOperations.updateFirst(query, update, YourEntity.class);



   - `updateMulti(Query query, Update update, Class<T> entityClass)`: Updates multiple documents matching the query.

    
Query query = new Query(Criteria.where("field1").is("value1"));
     Update update = new Update().set("field2", "new value");
     mongoOperations.updateMulti(query, update, YourEntity.class);



4. Delete Documents:
   - remove(Query query, Class<T> entityClass)`: Removes documents matching the query.

    
Query query = new Query(Criteria.where("field1").is("value1"));
     mongoOperations.remove(query, YourEntity.class);

    

   - remove(Object object)`: Removes the given document.

    
YourEntity entity = new YourEntity("value1", "value2");
     mongoOperations.remove(entity);

    

5. Aggregation:
   - aggregate(TypedAggregation<T> aggregation, Class<O> outputType)`: Performs an aggregation operation.
    
    
TypedAggregation<YourEntity> agg = newAggregation(
         match(Criteria.where("field1").is("value1")),
         group("field2").count().as("count")
     );
     AggregationResults<AggregationResult> results = mongoOperations.aggregate(agg, AggregationResult.class);
     List<AggregationResult> resultList = results.getMappedResults();

    

6. Indexing:
   - indexOps(Class<T> entityClass)`: Provides access to index operations for the specified entity class.
    
    
IndexOperations indexOps = mongoOperations.indexOps(YourEntity.class);
     indexOps.ensureIndex(new Index().on("field1", Sort.Direction.ASC));

    

These are just a few examples of the methods available in `MongoOperations`. You can explore the Spring Data MongoDB documentation for more details and additional methods to suit your specific use cases.

Comments