/notes/code/java/QuickTour.java (2dab14bb4e747df8c180cf7f13aee8e792ec5aa6) (6942 bytes) (mode 100644) (type blob)

/*
 * Copyright 2008-present MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This file was edited to match our guidelines
 * and add snippets.
 * It can be executed from this folder using
 * java -cp .:../../lib/mongo-java-driver-3.9.1.jar QuickTour.java
 */
package tour;

import static com.mongodb.client.model.Accumulators.sum;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Filters.gt;
import static com.mongodb.client.model.Filters.gte;
import static com.mongodb.client.model.Filters.lt;
import static com.mongodb.client.model.Filters.lte;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Sorts.descending;
import static com.mongodb.client.model.Updates.inc;
import static com.mongodb.client.model.Updates.set;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import org.bson.Document;

/** The QuickTour code example */
public class QuickTour {
  /**
   * Run this main method to see the output of this quick example.
   *
   * @param args takes an optional single argument for the connection string
   */
  public static void main(final String[] args) {

    // start snippet mongoclient
    MongoClient mongoClient;

    if (args.length == 0) {
      // connect to the local database server
      mongoClient = MongoClients.create();
    } else {
      mongoClient = MongoClients.create(args[0]);
    }
    // end snippet mongoclient

    // start snippet db-and-collection
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    // end snippet db-and-collection

    // drop all the data in it
    collection.drop();

    // start snippet document-creation
    // make a document and insert it
    Document doc =
        new Document("name", "MongoDB")
            .append("type", "database")
            .append("count", 1)
            .append("info", new Document("x", 203).append("y", 102));

    collection.insertOne(doc);
    // end snippet document-creation

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // start snippet documents-creation
    // now, lets add lots of little documents to the collection so we can explore queries and
    // cursors
    List<Document> documents = new ArrayList<Document>();
    for (int i = 0; i < 100; i++) {
      documents.add(new Document("i", i));
    }
    collection.insertMany(documents);
    // end snippet documents-creation
    System.out.println(
        "total # of documents after inserting 100 small ones (should be 101) "
            + collection.countDocuments());

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
      }
    } finally {
      cursor.close();
    }

    for (Document cur : collection.find()) {
      System.out.println(cur.toJson());
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
      }
    } finally {
      cursor.close();
    }

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

    try {
      while (cursor.hasNext()) {
        System.out.println(cursor.next().toJson());
      }
    } finally {
      cursor.close();
    }

    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    Consumer<Document> printBlock =
        new Consumer<Document>() {
          @Override
          public void accept(final Document document) {
            System.out.println(document.toJson());
          }
        };
    collection.find(gt("i", 50)).forEach(printBlock);

    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());

    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());

    // Aggregation
    collection
        .aggregate(
            asList(
                match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}"))))
        .forEach(printBlock);

    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), set("i", 110));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("i", 110));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());

    // Create Index
    collection.createIndex(new Document("i", 1));

    // Clean up
    // database.drop();

    // release resources
    mongoClient.close();
  }
}


Mode Type Size Ref File
100644 blob 15398 ee75155d2d99639acd17d31b2cc23cd752078e7e CONTRIB.md
100644 blob 20625 25b8e45e7f103089fb70fae5a219f09a29ef5312 KNOWN_BUGS.md
100644 blob 17217 e5c1f9f898cca948da42333b100e331d62b61d3c LICENSE.md
100644 blob 1997 f8801648fd4ba5843a2cbca8b10e4f69ba5d9b25 Makefile
100644 blob 6695 0b91924ffc7b73e2d36150369d4fd41a44b099c5 README.md
040000 tree - eb7afc38251ada69e1967e1ce3e49967eca2267c install
040000 tree - f16b283429b64b620b3bd7681a446ff54d504f84 notes
Hints:
Before first commit, do not forget to setup your git environment:
git config --global user.name "your_name_here"
git config --global user.email "your@email_here"

Clone this repository using HTTP(S):
git clone https://rocketgit.com/user/caubert/CSCI_3410

Clone this repository using ssh (do not forget to upload a key first):
git clone ssh://rocketgit@ssh.rocketgit.com/user/caubert/CSCI_3410

Clone this repository using git:
git clone git://git.rocketgit.com/user/caubert/CSCI_3410

You are allowed to anonymously push to this repository.
This means that your pushed commits will automatically be transformed into a merge request:
... clone the repository ...
... make some changes and some commits ...
git push origin main