import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
@Service
public class AdvancedMongoDBService {
@Autowired
private MongoTemplate mongoTemplate;
public void removeById(String id) {
Query query = new Query(Criteria.where("_id").is(id));
DeleteResult remove = mongoTemplate.remove(query, YourCollectionClass.class);
System.out.println(remove.getDeletedCount());
}
public void updateDocument(String id, String field, String newValue) {
Query query = new Query(Criteria.where("_id").is(id));
Update update = new Update();
update.set(field, newValue);
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, YourCollectionClass.class);
System.out.println(updateResult.getModifiedCount());
}
public void updateMultipleDocuments(String field, String newValue) {
Query query = new Query(Criteria.where(field).exists(true));
Update update = new Update();
update.set(field, newValue);
UpdateResult updateResult = mongoTemplate.updateMulti(query, update, YourCollectionClass.class);
System.out.println(updateResult.getModifiedCount());
}
public void incrementField(String id, String field, int incrementBy) {
Query query = new Query(Criteria.where("_id").is(id));
Update update = new Update();
update.inc(field, incrementBy);
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, YourCollectionClass.class);
System.out.println(updateResult.getModifiedCount());
}
public void pushElementToArray(String id, String field, Object element) {
Query query = new Query(Criteria.where("_id").is(id));
Update update = new Update();
update.p
评论已关闭