Skip to content

Instantly share code, notes, and snippets.

@LorisBachert
Last active January 25, 2016 11:57
Show Gist options
  • Save LorisBachert/6e4b05a8ad34bcb7be8e to your computer and use it in GitHub Desktop.
Save LorisBachert/6e4b05a8ad34bcb7be8e to your computer and use it in GitHub Desktop.
CRUD operations for MongoDB using Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDAO {
private static final String SERVER_URL = "";
private static final String USER = "";
private static final String PASSWORD = "";
private static final String DATABASE = "";
private static final String COLLECTION = "";
private static final String FSCOLLECTION = "";
private MongoCredential credential = MongoCredential.createCredential(USER, database, PASSWORD.toCharArray());
private MongoClient client;
public void create(Document document) throws Exception {
getCollection().insertOne(document);
}
public List<Document> read(Document filter) throws Exception {
final List<Document> result = new ArrayList<Document>();
FindIterable<Document> iterable = getCollection().find(filter);
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
result.add(document);
}
});
return result;
}
public void update(Document filter, Document update) throws Exception {
getCollection().updateMany(filter, update);
}
public void updateOne(Document filter, Document update) throws Exception {
getCollection().updateOne(filter, update);
}
public void delete(Document filter) throws Exception {
getCollection().deleteMany(filter);
}
public void deleteOne(Document filter) throws Exception {
getCollection().deleteOne(filter);
}
public InputStream getStream(String id) throws Exception {
@SuppressWarnings("deprecation")
GridFS gfsPhoto = new GridFS(getClient().getDB(FSCOLLECTION));
GridFSDBFile file = gfsPhoto.findOne(new ObjectId(id));
if (file == null) {
return null;
} else {
return file.getInputStream();
}
}
private MongoCollection<Document> getCollection() throws Exception {
MongoDatabase database = getDatabase();
MongoCollection<Document> collection = database.getCollection(MongoDAO.COLLECTION);
return collection;
}
private MongoDatabase getDatabase() throws Exception {
MongoDatabase database = getClient().getDatabase(MongoDAO.DATABASE);
return database;
}
private MongoClient getClient() throws Exception {
if (client == null) {
client = new MongoClient(new ServerAddress(SERVER_URL), Arrays.asList(credential));
}
return client;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment