Example usage for com.mongodb.client MongoCollection insertOne

List of usage examples for com.mongodb.client MongoCollection insertOne

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection insertOne.

Prototype

void insertOne(TDocument document);

Source Link

Document

Inserts the provided document.

Usage

From source file:mongodb.QuickTourAdmin.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args/*from  w ww  .j ava 2  s . c  o  m*/
 *            takes an optional single argument for the connection string
 */
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the specified database server
        mongoClient = new MongoClient("10.9.17.105", 27017);
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "test" database
    MongoDatabase database = mongoClient.getDatabase("test");

    database.drop();

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

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

    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }

    // drop a database
    mongoClient.getDatabase("databaseToBeDropped").drop();

    // create a collection
    database.createCollection("cappedCollection",
            new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }

    // drop a collection:
    collection.drop();

    // create an ascending index on the "i" field
    // 1 ascending or -1 for descending
    collection.createIndex(new Document("i", 1));

    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index.toJson());
    }

    // create a text index on the "content" field
    // text indexes to support text search of string content
    collection.createIndex(new Document("content", "text"));

    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    long matchCount = collection.count(text("textual content -irrelevant"));
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    Bson textSearch = text("textual content -irrelevant", "english");
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    Document myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc.toJson());

    // Run a command
    Document buildInfo = database.runCommand(new Document("buildInfo", 1));
    System.out.println(buildInfo);

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

From source file:mongome.MongoWriter.java

public void addUsers(ArrayList<User> usersList) {

    try {/* w w  w  .  j a v a  2  s.co m*/
        MongoDatabase db = mongoClient.getDatabase("reserva_bilhetes");
        System.out.println(">> Database connection sucessful!");

        MongoCollection col = db.getCollection("utilizadores");

        for (User usr : usersList) {
            Document doc = new Document();
            doc.put("_id", usr.getUsername());
            doc.put("nome", usr.getNome());
            doc.put("password", usr.getPassword());
            doc.put("email", usr.getEmail());
            doc.put("nif", usr.getNIF());
            doc.put("morada", usr.getMorada());

            col.insertOne(doc);
            System.out.println("User " + usr.getNome() + " added!");

        }
    } catch (Exception e) {
        System.out.println(e);
    }

}

From source file:mongome.MongoWriter.java

public void addReserva(ArrayList<Reserva> reservaList) {

    try {// w w w . j av  a2 s  .  co  m
        MongoDatabase db = mongoClient.getDatabase("reserva_bilhetes");
        System.out.println(">> Database connection sucessful!");

        MongoCollection col = db.getCollection("reservas");

        for (Reserva r : reservaList) {
            Document doc = new Document();
            doc.put("_id", r.getId());
            doc.put("username", r.getUsername());
            doc.put("data_reserva", r.getDataRes());
            doc.put("id_comboio", r.getIdComboio());
            doc.put("preco", r.getPreco());
            doc.put("origem", r.getOrigem());
            doc.put("destino", r.getDestino());
            doc.put("horaPartida", r.getHoraPartida());
            doc.put("horaChegada", r.getHoraChegada());
            List<BasicDBObject> lugares = new ArrayList<>();

            for (Seat s : r.getLugares()) {
                BasicDBObject tmp = new BasicDBObject();
                tmp.put("numero", s.getNumero());
                tmp.put("carruagem", s.getCarruagem());
                tmp.put("classe", s.getClasse());
                lugares.add(tmp);
            }
            doc.put("lugares", lugares);

            if (doc != null)
                col.insertOne(doc);
            System.out.println("Reserva " + r.getId() + " added!");

        }
    } catch (Exception e) {
        System.out.println(e);
    }

}

From source file:mongome.MongoWriter.java

public void addComboios(ArrayList<Train> trainList) {

    try {//  w w  w.  ja v a 2s .c o  m
        MongoDatabase db = mongoClient.getDatabase("reserva_bilhetes");
        System.out.println(">> Database connection sucessful!");

        MongoCollection col = db.getCollection("comboios");

        for (Train t : trainList) {
            Document doc = new Document();
            doc.put("_id", t.getId_Comboio());
            doc.put("lotaco", t.getLotacao());
            doc.put("nome", t.getNome());

            List<BasicDBObject> lugares = new ArrayList<>();
            for (Seat s : t.getLugares()) {
                BasicDBObject tmp = new BasicDBObject();
                tmp.put("numero", s.getNumero());
                tmp.put("carruagem", s.getCarruagem());
                tmp.put("classe", s.getClasse());
                lugares.add(tmp);
            }
            doc.put("lugares", lugares);

            if (doc != null)
                col.insertOne(doc);
            System.out.println("Comboio " + t.getNome() + " added!");

        }
    } catch (Exception e) {
        System.out.println(e);
    }

}

From source file:mongoSample.MongoSample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args//from  ww  w  .  j  av a 2 s. com
 *            takes an optional single argument for the connection string
 */
public static void main(final String[] args) {
    String mongoServer = args[0];

    MongoClient mongoClient = new MongoClient(mongoServer);
    MongoDatabase database = mongoClient.getDatabase("sakila");
    MongoCollection<Document> collection = database.getCollection("test");

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

    // 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);

    // 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());

    // 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);
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + collection.count());

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc);
    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
    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(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());

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

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100),
            new Document("$inc", new Document("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());

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));
    // collection.find().forEach(printBlock);

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

    // release resources
    mongoClient.close();
}

From source file:mongoSample.MyMongoDemo.java

License:Apache License

public static void main(final String[] args) {
    String mongoServer = args[0];

    MongoClient mongoClient = new MongoClient(mongoServer);
    MongoDatabase database = mongoClient.getDatabase("NGDBDemo");
    MongoCollection<Document> collection = database.getCollection("test");

    collection.drop();// ww w  . ja  v a  2  s .  co m

    Document people = new Document(); // A document for a person
    people.put("Name", "Guy");
    people.put("Email", "guy@gmail.com");

    BasicDBList friendList = new BasicDBList(); // A list for the persons
    // friends

    BasicDBObject friendDoc = new BasicDBObject(); // A document for each
    // friend

    friendDoc.put("Name", "Jo");
    friendDoc.put("Email", "Jo@gmail.com");
    friendList.add(friendDoc);
    friendDoc.clear();
    friendDoc.put("Name", "John");
    friendDoc.put("Email", "john@gmail.com");
    friendList.add(friendDoc);
    people.put("Friends", friendDoc);

    collection.insertOne(people);

    System.out.println('1');
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next().toJson());
        }
    } finally {
        cursor.close();
    }
    System.out.println('2');

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

    System.out.println('3');
    // now use a query to get 1 document out
    Document myDoc = collection.find(eq("Name", "Guy")).first();
    System.out.println(myDoc.toJson());

    database = mongoClient.getDatabase("sakila");
    collection = database.getCollection("films");
    for (Document cur : collection.find()) {
        System.out.println(cur.toJson());
    }
    mongoClient.close();
}

From source file:mongotweet.MongoTweet.java

public static void insertDocument(String collection, Document obj) {
    MongoCollection coll = db.getCollection(collection);
    coll.insertOne(obj);
}

From source file:mongotwitter.MongoTwitter.java

public boolean signup(String username, String password) {
    MongoCollection<Document> users = db.getCollection("users");
    Document oldDoc = users.find(eq("username", username)).first();
    if (oldDoc != null) {
        System.out.println("* Signup failed : Username already exists");
        return false;
    } else {//w ww  .jav  a2s. c om
        Document doc = new Document("username", username).append("password", password);
        users.insertOne(doc);
        System.out.println("* User @" + username + " is succesfully signed up");
        //autologin
        nick = username;
        System.out.println("* Welcome to MongoTwitter, @" + username + "!");
        return true;
    }
}

From source file:mongotwitter.MongoTwitter.java

public void follow(String followed) {
    if (followed.equals(nick)) {
        System.out.println("* Follow failed : You cannot follow yourself");
    } else {//from ww  w  .ja v  a 2s . c o m
        MongoCollection<Document> users = db.getCollection("users");
        Document oldDoc = users.find(eq("username", followed)).first();
        if (oldDoc == null) {
            System.out.println("* Follow failed : Username does not exist");
        } else {
            MongoCollection<Document> friends = db.getCollection("friends");
            Document frDoc = friends.find(and(eq("username", nick), eq("friend", followed))).first();
            if (frDoc != null) {
                System.out.println("* Follow failed : You already followed @" + followed);
            } else {
                MongoCollection<Document> followers = db.getCollection("followers");
                Date ts = new Date();
                Document friendDoc = new Document("username", nick).append("friend", followed).append("since",
                        ts);
                Document followerDoc = new Document("username", followed).append("follower", nick)
                        .append("since", ts);
                friends.insertOne(friendDoc);
                followers.insertOne(followerDoc);
                System.out.println("* You successfully followed " + followed);
            }
        }
    }
}

From source file:mongotwitter.MongoTwitter.java

public void tweet(String body) {
    final ObjectId tweet_id = new ObjectId();
    final Date time = new Date();
    MongoCollection<Document> tweets = db.getCollection("tweets");
    MongoCollection<Document> userline = db.getCollection("userline");
    MongoCollection<Document> timeline = db.getCollection("timeline");
    MongoCollection<Document> followers = db.getCollection("followers");

    Document tweetDoc = new Document("tweet_id", tweet_id).append("username", nick).append("body", body);

    Document userDoc = new Document("username", nick).append("time", time).append("tweet_id", tweet_id);

    List<Document> timelineList = new ArrayList<>();
    List<Document> followerList = followers.find(eq("username", nick)).into(new ArrayList<Document>());
    for (Document doc : followerList) {
        String follower = (String) doc.get("follower");
        Document timeDoc = new Document("username", follower).append("time", time).append("tweet_id", tweet_id);
        timelineList.add(timeDoc);// www .ja va2  s.  c  o  m
    }

    tweets.insertOne(tweetDoc);
    userline.insertOne(userDoc);
    timeline.insertMany(timelineList);

    System.out.println("* You tweeted \"" + body + "\" at " + time);
}