Initiaitng the MongoDb Conn

MongoOperations template = new MongoTemplate(new SimpleMongoClientDbFactory(MongoClients.create(), "database"));
 template.insert(p);
 template.findById(p.getId(), Person.class);
 template.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
 p = template.findOne(query(where("name").is("Joe")), Person.class); 
 template.remove(p);
 List<Person> people =  template.findAll(Person.class);//findign all the people with class Person and taking them into a LIST 
 template.dropCollection(Person.class);//Removing all the documents with Person Class
  • Save perfroms insert if document not there
void save / insert (Object objectToSave, String collectionName);

##### save(new Object(),Students);
##### 
##### 
##### // insert gives error if the id is already present 
##### // save overwrites

Id Convention

public class PlainStringId {
  @MongoId String id;
}

public class PlainObjectId {
  @MongoId ObjectId id;
}

public class StringToObjectId {
  @MongoId(FieldType.OBJECT_ID) String id;
}

Naming the Collection

@Document //Collection Name

  • updateFirst: Updates the first document that matches the query document criteria with the updated document.

  • updateMulti: Updates all objects that match the query document criteria with the updated document. The Update class contains the following methods:


  • Update addToSet (String key, Object value): Update using the $addToSet update modifier
  • Update currentDate (String key): Update using the $currentDate update modifier
  • Update currentTimestamp (String key): Update using the $currentDate update modifier with $type timestamp
  • Update inc (String key, Number inc): Update using the $inc update modifier
  • Update max (String key, Object max): Update using the $max update modifier
  • Update min (String key, Object min): Update using the $min update modifier
  • Update multiply (String key, Number multiplier): Update using the $mul update modifier
  • Update pop (String key, Update.Position pos): Update using the $pop update modifier
  • Update pull (String key, Object value): Update using the $pull update modifier
  • Update pullAll (String key, Object[] values): Update using the $pullAll update modifier
  • Update push (String key, Object value): Update using the $push update modifier
  • Update pushAll (String key, Object[] values): Update using the $pushAll update modifier
  • Update rename (String oldName, String newName): Update using the $rename update modifier
  • Update set (String key, Object value): Update using the $set update modifier
  • Update setOnInsert (String key, Object value): Update using the $setOnInsert update modifier
  • Update unset (String key): Update using the $unset update modifier

Person tom = template.insert(new Person("Motte", 21)); 
Query query = Query.query(Criteria.where("firstName").is(tom.getFirstName())); 
tom.setFirstname("Tom"); 
template.replace(query, tom, ReplaceOptions.none()); 
  1. Insert a new document.
  2. The query used to identify the single document to replace.
  3. Set up the replacement document which must hold either the same _id as the existing or no _id at all.
  4. Run the replace operation. .Replace one with upsert

template.insert(new Person("Tom", 21));
template.insert(new Person("Dick", 22));
template.insert(new Person("Harry", 23));

Query query = new Query(Criteria.where("firstName").is("Harry"));
Update update = new Update().inc("age", 1);

Person oldValue = template.update(Person.class)
 .matching(query)
 .apply(update)
 .findAndModifyValue(); // oldValue.age == 23

Person newValue = template.query(Person.class)
 .matching(query)
 .findOneValue(); // newValye.age == 24

Person newestValue = template.update(Person.class)
 .matching(query)
 .apply(update)
 .withOptions(FindAndModifyOptions.options().returnNew(true)) // Now return the newly updated document when updating
 .findAndModifyValue(); // newestValue.age == 25

Optional<User> result = template.update(Person.class)      
   matching(query(where("firstame").is("Tom")))(1)          
   .replaceWith(new Person("Dick"))(2)
   .withOptions(FindAndReplaceOptions.options().upsert()) (3)
   .as(User.class)(4)                                        
   .findAndReplace();(5)                 

(1) Use the fluent update API with the domain type given for mapping the query and deriving the collection name or just use MongoOperations#findAndReplace. (2) The actual match query mapped against the given domain type. Provide sort, fields and collation settings via the query. (3) Additional optional hook to provide options other than the defaults, like upsert. (4) An optional projection type used for mapping the operation result. If none given the initial domain type is used. (5) Trigger the actual processing. Use findAndReplaceValue to obtain the nullable result instead of an Optional.


Remove

  1. template.remove(tywin, "GOT");

    • Remove a single entity specified by its _id from the associated collection.
  2. template.remove(query(where("lastname").is("lannister")), "GOT");

    • Remove all documents that match the criteria of the query from the GOT collection.
  3. template.remove(new Query().limit(3), "GOT");

    • Remove the first three documents in the GOT collection. Unlike the previous method, the documents to remove are identified by their _id, running the given query, applying sort, limit, and skip options first, and then removing all at once in a separate step.
  4. template.findAllAndRemove(query(where("lastname").is("lannister")), "GOT");

    • Remove all documents matching the criteria of the query from the GOT collection. Unlike the previous method, documents do not get deleted in a batch but one by one.
  5. template.findAllAndRemove(new Query().limit(3), "GOT");

    • Remove the first three documents in the GOT collection. Unlike the previous method, documents do not get deleted in a batch but one by one.