List of usage examples for com.mongodb.client MongoCollection find
FindIterable<TDocument> find();
From source file:codeu.chat.server.Controller.java
License:Apache License
private void loadMessages() { MongoCollection<Document> messages = database.getMessagesCollection(); int errorCount = 0; int messageCount = 0; //Sort messages, oldest-to-newest try (MongoCursor<Document> cursor = messages.find().sort(new BasicDBObject("creation", 1)).iterator()) { while (cursor.hasNext()) { Document doc = cursor.next(); final Uuid messageID = buildUuid(doc.getInteger("id")); final Uuid conversationID = buildUuid(doc.getInteger("conversation")); Conversation foundConversation = model.conversationById().first(conversationID); final Uuid authorID = buildUuid(doc.getInteger("author")); User foundUser = model.userById().first(authorID); if (foundUser != null && foundConversation != null && isIdFree(messageID)) { Time creation = Time.fromMs(doc.getLong("creation")); String content = doc.getString("content"); model.add(new Message(messageID, Uuid.NULL, Uuid.NULL, creation, foundUser.id, content)); // Find and update the previous "last" message so that it's "next" value // will point to the new message. if (Uuid.equals(foundConversation.lastMessage, Uuid.NULL)) { // The conversation has no messages in it, that's why the last message is NULL (the first // message should be NULL too. Since there is no last message, then it is not possible // to update the last message's "next" value. } else { final Message lastMessage = model.messageById().first(foundConversation.lastMessage); lastMessage.next = messageID; }// w ww .java 2 s .c om // If the first message points to NULL it means that the conversation was empty and that // the first message should be set to the new message. Otherwise the message should // not change. if (Uuid.equals(foundConversation.firstMessage, Uuid.NULL)) { foundConversation.firstMessage = messageID; } // Update the conversation to point to the new last message as it has changed. foundConversation.lastMessage = messageID; if (!foundConversation.users.contains(foundUser.id)) { foundConversation.users.add(foundUser.id); } LOG.info("Loaded Message: \nid: %s\nauthor: %s\nconversation: %s\ncontent: %s\ncreation: %s\n", messageID, foundUser.name, foundConversation.title, content, creation); messageCount++; } else { LOG.info("Loading Message failure. No user/conversation found or ID is in use: " + messageID); errorCount++; } } LOG.info("Successfully loaded %d messages. Failed to load %d messages.\n", messageCount, errorCount); } }
From source file:com.andersen.backendjaxrsproject.EmployeeServices.java
public String addEmployee(Employee employee) { String jsonString = ""; try {/* w w w .j a v a 2 s .c o m*/ ObjectMapper mapper = new ObjectMapper(); MongoCollection<Document> employeeCollection = employeeDB.getCollection("EmployeeCollection"); employee.setId(employeeCount + 1); jsonString = mapper.writeValueAsString(employee); Document doc = Document.parse(jsonString); employeeCollection.insertOne(doc); //get the document back from the database to verify that it was added Bson bson = (Bson) com.mongodb.util.JSON.parse("{'id': " + employee.getId() + "}"); FindIterable<Document> find = employeeCollection.find(); FindIterable<Document> filteredQuery = find.filter(bson); String newString = ""; for (Document document : filteredQuery) { newString = newString + document.toJson() + "\n"; } return newString; } catch (JsonProcessingException ex) { Logger.getLogger(EmployeeServices.class.getName()).log(Level.SEVERE, null, ex); } return jsonString; }
From source file:com.andersen.backendjaxrsproject.EmployeeServices.java
public String getAllEmployees() { MongoCollection<Document> employeeCollection = employeeDB.getCollection("EmployeeCollection"); FindIterable<Document> find = employeeCollection.find(); String returnString = ""; for (Document document : find) { returnString = returnString + document.toJson() + "\n"; }/*from w w w. j ava 2 s. c o m*/ return returnString; }
From source file:com.andersen.backendjaxrsproject.EmployeeServices.java
public String getEmployeebyID(String id) { MongoCollection<Document> employeeCollection = employeeDB.getCollection("EmployeeCollection"); Bson bson = (Bson) com.mongodb.util.JSON.parse("{'id': " + id + "}"); FindIterable<Document> find = employeeCollection.find(); FindIterable<Document> filteredQuery = find.filter(bson); String newString = ""; for (Document document : filteredQuery) { newString = newString + document.toJson() + "\n"; }/* w ww. j a v a2 s.c om*/ return newString; }
From source file:com.andersen.backendjaxrsproject.EmployeeServices.java
public String getEmployeebyLastName(String lastName) { MongoCollection<Document> employeeCollection = employeeDB.getCollection("EmployeeCollection"); Bson bson = (Bson) com.mongodb.util.JSON.parse("{'lastName': '" + lastName + "'}"); FindIterable<Document> find = employeeCollection.find(); FindIterable<Document> filteredQuery = find.filter(bson); String newString = ""; for (Document document : filteredQuery) { newString = newString + document.toJson() + "\n"; }//from www. j a v a 2 s .c o m return newString; }
From source file:com.andersen.backendjaxrsproject.EmployeeServices.java
public String updateEmployee(long employeeID, String key, String updatedValue) { String newString = ""; MongoCollection<Document> employeeCollection = employeeDB.getCollection("EmployeeCollection"); ObjectMapper mapper = new ObjectMapper(); Bson newValue = new Document(key, updatedValue); Bson filter = new Document("id", employeeID); Bson updateOperationDoc = new Document("$set", newValue); //Update the employee information UpdateResult result = employeeCollection.updateOne(filter, updateOperationDoc); //get the document back from the database to verify that it was added Bson bson = (Bson) com.mongodb.util.JSON.parse("{'id': " + employeeID + "}"); FindIterable<Document> find = employeeCollection.find(); FindIterable<Document> filteredQuery = find.filter(bson); for (Document document : filteredQuery) { newString = newString + document.toJson() + "\n"; }//from w ww . j a v a 2 s . c om return newString; }
From source file:com.avbravo.jgmongodesktopexample.Start.java
/** * @param args the command line arguments *//*from w ww .j a v a2 s. c o m*/ public static void main(String[] args) { // TODO code application logic here try { PaisesFacade paisesFacade = new PaisesFacade(); SedesFacade sedesFacade = new SedesFacade(); ProvinciasFacade provinciasFacade = new ProvinciasFacade(); MongoClient client = new MongoClient("localhost", 27017); MongoDatabase database = client.getDatabase("fantasy"); MongoCollection<Document> collection = database.getCollection("paises"); List<Document> documents = (List<Document>) collection.find().into(new ArrayList<Document>()); //Document document = new Document("name","Cuba") // .append("poblacion", 7777); // // collection.insertOne(document); // DBCollection coll = database.getCollection("mycol"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a"); Date startDate = simpleDateFormat.parse(simpleDateFormat.format(new Date())); MongoCollection<BasicDBObject> coll = database.getCollection("paises", BasicDBObject.class); BasicDBObject doc = new BasicDBObject("title", "OrientDB").append("Fecha", startDate) .append("url", "http://www.tutorialspoint.com/mongodb/").append("by", "tutorials point"); coll.insertOne(doc); for (Document document : documents) { System.out.println(document); System.out.println("Siglas" + document.get("Siglas")); System.out.println("Pais" + document.get("Pais")); } // // List<Provincias> list = provinciasFacade.findAll(); // list.forEach((p) -> { // System.out.println(" "+p.toString()); // }); // // Provincias provincias = new Provincias(); // provincias.setIdprovincia("6"); // Provincias pr = provinciasFacade.findById(provincias); // // if(pr.getIdprovincia() == null){ // System.out.println("---> no hay provincia con ese id"); // }else{ // System.out.println("---> "+pr.toString()); // } // Paises paises = new Paises(); // paises.setSiglas("pa"); // Paises p = paisesFacade.findById(paises); // // if(p.getSiglas() == null){ // System.out.println("============================"); // System.out.println("no hay paises con siglas "+paises.getSiglas()); // }else{ // System.out.println("paises: "+p.toString()); // } // Provincias provincias = new Provincias(); // provincias.setIdprovincia("2"); // provincias.setProvincia("Cocle"); // provincias.setPaises(p); // // provincias.setHola("Hola"); // // if(provinciasFacade.save(provincias)){ // System.out.println("guardado"); // }else{ // System.out.println("no se guardo"); // } // // List<Paises> list = paisesFacade.findAll(); // Sedes sedes = new Sedes(); // sedes.setIdsede("s-2"); // sedes.setSede("Sede 2"); // sedes.setPaises(list); // sedesFacade.save(sedes); // } catch (Exception e) { System.out.println("error " + e.getLocalizedMessage()); } }
From source file:com.bdnc.ecommercebdnc.dao.DAODocumentos.java
public List<Compra> buscarCompras() { MongoClient client = new MongoClient("localhost", 27017); MongoDatabase dataBase = client.getDatabase("ecommerce-bdnc"); MongoCollection<Document> collection = dataBase.getCollection("vendas"); List<Compra> compras = new ArrayList<>(); MongoCursor<Document> cursor = collection.find().iterator(); while (cursor.hasNext()) { Compra compra = new Compra(); compras.add(compra.fromDocument(cursor.next())); }/*from ww w . ja va 2 s. c o m*/ client.close(); return compras; }
From source file:com.cognifide.aet.vs.metadata.MetadataDAOMongoDBImpl.java
License:Apache License
@Override public List<Suite> listSuites(DBKey dbKey) throws StorageException { MongoCollection<Document> metadata = getMetadataCollection(dbKey); LOGGER.debug("Fetching all suites for company: `{}`, project: `{}`.", dbKey.getCompany(), dbKey.getProject());/*from www . j a v a 2 s .c o m*/ final FindIterable<Document> found = metadata.find().sort(Sorts.descending(SUITE_VERSION_PARAM_NAME)); return FluentIterable.from(found).transform(new Function<Document, Suite>() { @Override public Suite apply(Document result) { return GSON.fromJson(result.toJson(), SUITE_TYPE); } }).toList(); }
From source file:com.cognitive.cds.invocation.mongo.IntentMappingDao.java
License:Apache License
public List<IntentMapping> getAll() { List<IntentMapping> intentList = new ArrayList<IntentMapping>(); mongoDbDao.setDatabase("intent"); MongoCollection<Document> collection = mongoDbDao.getCollection("cdsintent"); FindIterable<Document> docs = collection.find(); for (Iterator iterator = docs.iterator(); iterator.hasNext();) { Document obj = (Document) iterator.next(); try {//from ww w .j a v a 2s.c om String json = obj.toJson(); IntentMapping im = mapper.readValue(json, IntentMapping.class); im.setId(im.get_id().toHexString()); // we do not need the _id if we set id im.set_id(null); intentList.add(im); if (cacheIntents == true && im != null) { cache.put(im.getName(), im); } } catch (IOException e) { logger.error("========> Deserialize: " + e.toString()); } } return intentList; }