public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");
    MongoCollection<Document> collection = db.getCollection("deleteTest");

    collection.drop();

    for (int idx = 1; idx <= 8; idx++) {
      collection.insertOne(new Document("_id", idx));
    }

    System.out.println("Before any deletes");
    List<Document> docs = collection.find().into(new ArrayList<Document>());
    for (Document doc : docs) {
      Helper.prettyPrintJSON(doc);
    }

    // delete 2,3,4

    collection.deleteMany(and(gte("_id", 2), lt("_id", 5)));
    System.out.println("removed gte2 lt5");
    docs = collection.find().into(new ArrayList<Document>());
    for (Document doc : docs) {
      Helper.prettyPrintJSON(doc);
    }

    collection.deleteOne(eq("_id", 8));
    System.out.println("Removed id 8");

    docs = collection.find().into(new ArrayList<Document>());
    for (Document doc : docs) {
      Helper.prettyPrintJSON(doc);
    }
  }
Пример #2
0
 @Override
 public void drop() {
   if (tx.started()) {
     tx.commit();
   }
   coll.drop();
 }
Пример #3
0
  public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    MongoDatabase mongoDatabase = client.getDatabase("course");
    MongoCollection<Document> collection = mongoDatabase.getCollection("findTest");

    collection.drop();

    // insert 10 documents with a random integer as the value of field "x"
    for (int i = 0; i < 10; i++) {
      collection.insertOne(new Document("x", new Random().nextInt(100)));
    }

    System.out.println("Find one:");
    Document one = collection.find().first();
    System.out.println(one);

    System.out.println("\nFind all: ");
    List<Document> all = collection.find().into(new ArrayList<Document>());
    System.out.println(all);

    System.out.println("\nFind all cursor: ");
    MongoCursor<Document> cursor = collection.find().iterator();
    try {

      while (cursor.hasNext()) {
        System.out.println(cursor.next());
      }

    } finally {
      cursor.close();
    }

    //        System.out.println("\nFind all: ");
    //        DBCursor cursor = collection.find();
    //        try {
    //          while (cursor.hasNext()) {
    //              DBObject cur = cursor.next();
    //              System.out.println(cur);
    //          }
    //        } finally {
    //            cursor.close();
    //        }
    //
    System.out.println("\nCount:");
    long count = collection.count();
    System.out.println(count);
  }
Пример #4
0
  public static void main(String[] args) {

    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");

    MongoCollection<Document> coll = db.getCollection("findWithSortTest");

    coll.drop();

    for (int i = 0; i < 8; i++) {
      coll.insertOne(new Document().append("_id", i));
    }

    // coll.deleteMany(Filters.gt("_id", 4));
    coll.deleteOne(Filters.eq("_id", 4));

    for (Document cur : coll.find().into(new ArrayList<Document>())) {
      System.out.println(cur);
    }
  }
Пример #5
0
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase database = client.getDatabase("course");
    MongoCollection<Document> collection = database.getCollection("deleteTest");

    collection.drop();

    // insert 8 documents, with _id set to the value of the loop variable
    for (int i = 0; i < 8; i++) {
      collection.insertOne(new Document().append("_id", i));
    }

    //        collection.deleteMany(gt("_id", 4));

    collection.deleteOne(eq("_id", 4));

    for (Document cur : collection.find().into(new ArrayList<Document>())) {
      Helpers.printJson(cur);
    }
  }
Пример #6
0
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");
    MongoCollection<Document> coll = db.getCollection("findWithFilterTest");
    coll.drop();

    for (int i = 0; i < 8; i++) {
      coll.insertOne(new Document().append("_id", i).append("x", i));
    }

    // coll.replaceOne(eq("x", 5),  new Document("_id", 5).append("x", 20).append("update", true));
    // coll.updateOne(eq("_id", 9), new Document("$set", new Document("x", 20)));
    // coll.updateOne(eq("_id", 9), new Document("$set", new Document("x", 20)), new
    // UpdateOptions().upsert(false));
    coll.updateMany(gte("_id", 5), new Document("$inc", new Document("x", 1)));

    List<Document> all = coll.find().into(new ArrayList<Document>());
    for (Document cur : all) {
      printJson(cur);
    }
  }
Пример #7
0
  public static void main(String[] args) {
    MongoClient client = new MongoClient();
    MongoDatabase db = client.getDatabase("course");
    MongoCollection<Document> coll = db.getCollection("findTest");
    coll.drop();

    for (int i = 0; i < 10; i++) {
      coll.insertOne(new Document("x", i));
    }

    System.out.println("Find one:");
    Document first = coll.find().first();
    printJson(first);

    System.out.println("Find all with into:");
    List<Document> all = coll.find().into(new ArrayList<Document>());
    for (Document cur : all) {
      printJson(cur);
    }

    System.out.println("Find all with iteration:");
    MongoCursor<Document> cursor = coll.find().iterator();
    try {
      while (cursor.hasNext()) {
        Document cur = cursor.next();
        printJson(cur);
      }

    } finally {
      // если выбросится исключение
      // так есть надежда, что поиск открытый на сервере закроется
      cursor.close();
    }

    System.out.println("Count:");
    long count = coll.count();
    System.out.println(count);
  }
Пример #8
0
  @Test
  public void index() {
    checkMinServerVersion(3.4);
    MongoCollection<Document> indexes = getDatabase().getCollection("indexes");
    MappedClass mappedClass = getMorphia().getMapper().getMappedClass(IndexedClass.class);

    indexes.drop();
    Index index =
        new IndexBuilder()
            .fields(
                new FieldBuilder().value("indexName"),
                new FieldBuilder().value("text").type(IndexType.DESC))
            .options(indexOptions());
    indexHelper.createIndex(indexes, mappedClass, index, false);
    List<DBObject> indexInfo = getDs().getCollection(IndexedClass.class).getIndexInfo();
    for (DBObject dbObject : indexInfo) {
      if (dbObject.get("name").equals("indexName")) {
        checkIndex(dbObject);

        assertEquals("en", dbObject.get("default_language"));
        assertEquals("de", dbObject.get("language_override"));

        assertEquals(
            new BasicDBObject()
                .append("locale", "en")
                .append("caseLevel", true)
                .append("caseFirst", "upper")
                .append("strength", 5)
                .append("numericOrdering", true)
                .append("alternate", "shifted")
                .append("maxVariable", "space")
                .append("backwards", true)
                .append("normalization", true)
                .append("version", "57.1"),
            dbObject.get("collation"));
      }
    }
  }
  public static void main(String[] args) {

    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldMongodbSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient();

    MongoDatabase db = client.getDatabase("course");

    final MongoCollection<Document> coll = db.getCollection("hello");

    coll.drop();

    coll.insertOne(new Document("name", "Mongodb"));

    Spark.get(
        new Route("/") {

          @Override
          public Object handle(Request arg0, Response arg1) {
            StringWriter writer = new StringWriter();
            try {
              Template helloTemplate = configuration.getTemplate("hello.ftl");

              Document document = coll.find().first();

              helloTemplate.process(document, writer);

              // System.out.println(writer);

            } catch (Exception e) {
              halt(500);
              e.printStackTrace();
            }
            return writer;
          }
        });
  }
Пример #10
0
  @Test
  public void oldIndexForm() {
    MongoCollection<Document> indexes = getDatabase().getCollection("indexes");
    MappedClass mappedClass = getMorphia().getMapper().getMappedClass(IndexedClass.class);

    indexes.drop();
    Index index =
        new IndexBuilder()
            .name("index_name")
            .background(true)
            .disableValidation(true)
            .dropDups(true)
            .expireAfterSeconds(42)
            .sparse(true)
            .unique(true)
            .value("indexName, -text");
    indexHelper.createIndex(indexes, mappedClass, index, false);
    List<DBObject> indexInfo = getDs().getCollection(IndexedClass.class).getIndexInfo();
    for (DBObject dbObject : indexInfo) {
      if (dbObject.get("name").equals("index_name")) {
        checkIndex(dbObject);
      }
    }
  }
Пример #11
0
  // insert into MongoDB(DBobject)
  public static void readInstallations(MongoDatabase db) {
    MongoCollection collection = db.getCollection("installations");
    // clean
    collection.drop();

    try (InputStream inputStream =
            CsvToMongoDb.class.getResourceAsStream("/batch/csv/installations.csv");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {

      MongoCollection<Document> coll = db.getCollection("installations");

      reader
          .lines()
          .skip(1)
          .filter(line -> line.length() > 0)
          .map(line -> line.split("\",\""))
          .forEach(
              columns -> {
                System.out.println("Une ligne");

                // String nom =
                // columns[0].matches("\".*\"")?columns[0].substring(2,columns[0].length()-1):columns[0];

                // String nom =
                // columns[0].matches("\".*\"")?columns[0].substring(1,columns[0].length()-1):columns[0];
                // System.out.println(nom);
                String nom = columns[0].substring(1, columns[0].length());
                System.out.println("nom = " + nom);
                String numeroInstall =
                    columns[1].matches("\".*\"")
                        ? columns[1].substring(1, columns[1].length() - 1)
                        : columns[1];
                System.out.println("numeroInstall = " + numeroInstall);
                String nomCommune =
                    columns[2].matches("\".*\"")
                        ? columns[2].substring(1, columns[2].length() - 1)
                        : columns[2];
                String codeInsee =
                    columns[3].matches("\".*\"")
                        ? columns[3].substring(1, columns[3].length() - 1)
                        : columns[3];
                String codePostal =
                    columns[4].matches("\".*\"")
                        ? columns[4].substring(1, columns[4].length() - 1)
                        : columns[4];
                String lieuDit =
                    columns[5].matches("\".*\"")
                        ? columns[5].substring(1, columns[5].length() - 1)
                        : columns[5];
                String numeroVoie =
                    columns[6].matches("\".*\"")
                        ? columns[6].substring(1, columns[6].length() - 1)
                        : columns[6];
                String nomVoie =
                    columns[7].matches("\".*\"")
                        ? columns[7].substring(1, columns[7].length() - 1)
                        : columns[7];
                String location =
                    columns[8].matches("\".*\"")
                        ? columns[8].substring(1, columns[8].length() - 1)
                        : columns[8];
                String longitude =
                    columns[9].matches("\".*\"")
                        ? columns[9].substring(1, columns[9].length() - 1)
                        : columns[9];
                String latitude =
                    columns[10].matches("\".*\"")
                        ? columns[10].substring(1, columns[10].length() - 1)
                        : columns[10];
                String accessibilite =
                    columns[11].matches("\".*\"")
                        ? columns[11].substring(1, columns[11].length() - 1)
                        : columns[11];
                String mobiliteReduite =
                    columns[12].matches("\".*\"")
                        ? columns[12].substring(1, columns[12].length() - 1)
                        : columns[12];
                String handicapesSensoriels =
                    columns[13].matches("\".*\"")
                        ? columns[13].substring(1, columns[13].length() - 1)
                        : columns[13];
                String empriseFonciere =
                    columns[14].matches("\".*\"")
                        ? columns[14].substring(1, columns[14].length() - 1)
                        : columns[14];
                String logementGardien =
                    columns[15].matches("\".*\"")
                        ? columns[15].substring(1, columns[15].length() - 1)
                        : columns[15];
                String multiCommune =
                    columns[16].matches("\".*\"")
                        ? columns[16].substring(1, columns[16].length() - 1)
                        : columns[16];
                String placeParking =
                    columns[17].matches("\".*\"")
                        ? columns[17].substring(1, columns[17].length() - 1)
                        : columns[17];
                String parkingHandicapes =
                    columns[18].matches("\".*\"")
                        ? columns[18].substring(1, columns[18].length() - 1)
                        : columns[18];
                String installPart =
                    columns[19].matches("\".*\"")
                        ? columns[19].substring(1, columns[19].length() - 1)
                        : columns[19];
                String metro =
                    columns[20].matches("\".*\"")
                        ? columns[20].substring(1, columns[20].length() - 1)
                        : columns[20];
                String bus =
                    columns[21].matches("\".*\"")
                        ? columns[21].substring(1, columns[21].length() - 1)
                        : columns[21];
                String tram =
                    columns[22].matches("\".*\"")
                        ? columns[22].substring(1, columns[22].length() - 1)
                        : columns[22];
                String train =
                    columns[23].matches("\".*\"")
                        ? columns[23].substring(1, columns[23].length() - 1)
                        : columns[23];
                String bateau =
                    columns[24].matches("\".*\"")
                        ? columns[24].substring(1, columns[24].length() - 1)
                        : columns[24];
                String autre =
                    columns[25].matches("\".*\"")
                        ? columns[25].substring(1, columns[25].length() - 1)
                        : columns[25];
                String nbEquip =
                    columns[26].matches("\".*\"")
                        ? columns[26].substring(1, columns[26].length() - 1)
                        : columns[26];
                String nbFichesEquip =
                    columns[27].matches("\".*\"")
                        ? columns[27].substring(1, columns[27].length() - 1)
                        : columns[27];
                String dateMaj =
                    columns[28].matches("\".*\"")
                        ? columns[28].substring(1, columns[28].length() - 1)
                        : columns[28];

                // Double [] coords = new Double [2];
                // coords[0] = Double.valueOf(latitude);
                // coords[1] = Double.valueOf(longitude);

                // System.out.println(coords[0]);

                Document doc =
                    new Document("_id", numeroInstall)
                        .append("nom", nom)
                        .append(
                            "adresse",
                            new Document()
                                .append("commune", nomCommune)
                                .append("numero", numeroVoie)
                                .append("voie", nomVoie)
                                .append("lieuDit", lieuDit)
                                .append("codePostal", codePostal))
                        .append(
                            "location",
                            new Document("type", "Point")
                                .append(
                                    "coordinates",
                                    Arrays.asList(
                                        Double.valueOf(columns[9]), Double.valueOf(columns[10]))))
                        .append("multiCommune", multiCommune.equals("Oui") ? true : false)
                        .append("nbPlacesParking", placeParking)
                        .append("nbPlacesParkingHandicapes", parkingHandicapes);
                // System.out.println(doc.toJson());
                // doc.put("equipements", new ArrayList<Document>());
                coll.insertOne(doc);
              });
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }