Skip to content

Instantly share code, notes, and snippets.

MongoClient mongoClient = new MongoClient("localhost");
MongoDatabase database = mongoClient.getDatabase("dbname");
MongoCollection collection = database.getCollection("collectionname");
Document exampleDoc = new Document();
exampleDoc.put("name","Lourenco");
exampleDoc.put("country","USA");
System.out.println(exampleDoc.toJson());
collection.insertOne(exampleDoc);
Document exampleDoc = new Document();
exampleDoc.put("name","Lourenco");
exampleDoc.put("country","USA");
Document exampleDoc2 = new Document();
exampleDoc2.put("name","John");
exampleDoc2.put("country","USA");
List<Document> multipleDocs = new ArrayList<>();
multipleDocs.add(exampleDoc);
multipleDocs.add(exampleDoc2);
collection.insertMany(multipleDocs);
FindIterable<Document> result = collection.find();
for(Document docFound : result){
 System.out.println(docFound.toJson());
}
Document filter = new Document("name","Lourenco");
FindIterable<Document> result2 = collection.find(filter);
for(Document docFound : result2){
 System.out.println(docFound.toJson());
}
package lourenco.tech.mongodb;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public JSONObject readJsonFromUrl(String url) {
JSONObject helloWorldAPI = readJsonFromUrl("https://<yourhost>/v3");
System.out.println(helloWorldAPI.toString());
private String rancherBearerToken;
private String rancherAddress;
private static String rancherProjects = "/v3/projects/";
private static String rancherWorkloads = "/workloads/";
public RancherClient() {
this("<yourhost>", "<yourtoken>");
}
public RancherClient(String rancherAddress, String token) {
public JSONArray getProjects() {
JSONArray returnArr = new JSONArray();
try {
JSONObject json = readJsonFromUrl("https://" + rancherAddress + rancherProjects);
JSONArray dataArr = json.getJSONArray("data");
for (int i = 0; i < dataArr.length(); i++) {
JSONObject dataObj = dataArr.getJSONObject(i);
JSONObject returnObj = new JSONObject();
returnObj.put("name", dataObj.get("name"));