Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

In this page you can find the example usage for com.mongodb DBCollection insert.

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:org.eclipselabs.restlet.mongo.MongoResource.java

License:Open Source License

@Post
public String add(JsonRepresentation representation) throws JSONException, UnknownHostException {
    JSONObject json = representation.getJsonObject();
    DBCollection collection = getCollection();
    DBObject dbObject = (DBObject) JSON.parse(json.toString());
    collection.insert(dbObject);
    return getReference().toString() + dbObject.get("_id").toString();
}

From source file:org.einherjer.week2.samples.DotNotationSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB db = client.getDB("course");
    DBCollection lines = db.getCollection("dotNotationSample");
    lines.drop();/*from w w  w . j ava  2  s.  co m*/
    Random rand = new Random();

    // insert 10 lines with random start and end points
    for (int i = 0; i < 10; i++) {
        lines.insert(
                new BasicDBObject("_id", i)
                        .append("start",
                                new BasicDBObject("x", rand.nextInt(90) + 10).append("y",
                                        rand.nextInt(90) + 10))
                        .append("end", new BasicDBObject("x", rand.nextInt(90) + 10).append("y",
                                rand.nextInt(90) + 10)));
    }

    QueryBuilder builder = QueryBuilder.start("start.x").greaterThan(50);

    DBCursor cursor = lines.find(builder.get(), new BasicDBObject("start.y", true).append("_id", false));

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

From source file:org.einherjer.week2.samples.FieldSelectionSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB db = client.getDB("course");
    DBCollection collection = db.getCollection("fieldSelectionSample");
    collection.drop();/*  w ww. j  a v a2  s.  c  o m*/
    Random rand = new Random();

    // insert 10 documents with two random integers
    for (int i = 0; i < 10; i++) {
        collection.insert(new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(100)).append("z",
                rand.nextInt(1000)));
    }

    DBObject query = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(70).get();

    //use second find parameter to filter the returned fields
    DBCursor cursor = collection.find(query, new BasicDBObject("y", true).append("_id", false));
    try {
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            System.out.println(cur);
        }
    } finally {
        cursor.close();
    }
}

From source file:org.einherjer.week2.samples.FindCriteriaSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB db = client.getDB("course");
    DBCollection collection = db.getCollection("findCriteriaSample");
    collection.drop();/*from w w w  .ja va 2 s  .c  o m*/

    // insert 10 documents with two random integers
    for (int i = 0; i < 10; i++) {
        collection
                .insert(new BasicDBObject("x", new Random().nextInt(2)).append("y", new Random().nextInt(100)));
    }

    //1- The query document can be created by using a QueryBuilder...
    QueryBuilder builder = QueryBuilder.start("x").is(0).and("y").greaterThan(10).lessThan(70);
    //2- or, the query document can be created manually
    DBObject query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt", 10).append("$lt", 90));

    System.out.println("\nCount:");
    long count = collection.count(builder.get());
    System.out.println(count);

    System.out.println("\nFind all: ");
    DBCursor cursor = collection.find(builder.get());
    try {
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            System.out.println(cur);
        }
    } finally {
        cursor.close();
    }
}

From source file:org.einherjer.week2.samples.FindSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB db = client.getDB("course");
    DBCollection collection = db.getCollection("findSample");
    collection.drop();//from  w  w w . ja v a  2 s.c om

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

    System.out.println("Find one:");
    DBObject one = collection.findOne();
    System.out.println(one);

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

From source file:org.einherjer.week2.samples.InsertSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB courseDB = client.getDB("course");
    DBCollection collection = courseDB.getCollection("insertSample");

    collection.drop();/*w w  w.jav  a2  s .  c o m*/

    DBObject doc = new BasicDBObject().append("x", 1);
    System.out.println(doc);
    collection.insert(doc);
    System.out.println(doc); //_id field gets generated

    DBObject doc2 = new BasicDBObject("_id", new ObjectId()).append("x", 1);
    System.out.println(doc2);
    collection.insert(doc2);
    System.out.println(doc2); //same as doc1

    DBObject doc3 = new BasicDBObject("_id", "123").append("x", 1);
    System.out.println(doc3);
    collection.insert(doc3);
    System.out.println(doc3); //_id field set by to a type different than ObjectId

    collection.insert(doc); //duplicate exception

}

From source file:org.einherjer.week2.samples.SortSkipLimitSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    Mongo client = new Mongo();
    DB db = client.getDB("course");
    DBCollection lines = db.getCollection("sortSkipLimitSample");
    lines.drop();//from   ww w .  j  a  va  2  s .c  o  m
    Random rand = new Random();

    // insert 10 lines with random start and end points
    for (int i = 0; i < 10; i++) {
        lines.insert(new BasicDBObject("_id", i)
                .append("start", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10))
                .append("end", new BasicDBObject("x", rand.nextInt(2)).append("y", rand.nextInt(90) + 10)));
    }

    DBCursor cursor = lines.find().sort(new BasicDBObject("start.x", 1).append("start.y", -1)).skip(2)
            .limit(10);

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

From source file:org.einherjer.week2.samples.UpdateRemoveSample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    DBCollection collection = createCollection();

    List<String> names = Arrays.asList("alice", "bobby", "cathy", "david", "ethan");
    for (String name : names) {
        collection.insert(new BasicDBObject("_id", name));
    }//from w w  w. j a va  2  s. c  o  m

    // see scratch method

    printCollection(collection);
}

From source file:org.exist.mongodb.xquery.mongodb.collection.Insert.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//from  www.j  a  v a2 s  . c o m
        // Verify clientid and get client
        String mongodbClientId = args[0].itemAt(0).getStringValue();
        MongodbClientStore.getInstance().validate(mongodbClientId);
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);

        // Get parameters
        String dbname = args[1].itemAt(0).getStringValue();
        String collection = args[2].itemAt(0).getStringValue();

        // Get database
        DB db = client.getDB(dbname);
        DBCollection dbcol = db.getCollection(collection);

        // Place holder for all results
        List<DBObject> allContent = new ArrayList<>();

        SequenceIterator iterate = args[3].iterate();
        while (iterate.hasNext()) {
            String value = iterate.nextItem().getStringValue();
            if (StringUtils.isEmpty(value)) {
                LOG.error("Skipping empty string");
            } else {
                BasicDBObject bsonContent = (BasicDBObject) JSON.parse(value);
                allContent.add(bsonContent);
            }
        }

        WriteResult result = dbcol.insert(allContent);

        return new StringValue(result.toString());

    } catch (MongoCommandException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0005, ex.getMessage());

    } catch (JSONParseException ex) {
        String msg = "Invalid JSON data: " + ex.getMessage();
        LOG.error(msg);
        throw new XPathException(this, MongodbModule.MONG0004, msg);

    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);

    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage());

    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        throw new XPathException(this, MongodbModule.MONG0003, t.getMessage());
    }

}

From source file:org.exoplatform.chat.services.mongodb.ChatServiceImpl.java

License:Open Source License

public void write(String message, String user, String room, String isSystem, String options) {
    DBCollection coll = db().getCollection(M_ROOM_PREFIX + room);

    message = StringUtils.chomp(message);
    message = message.replaceAll("&", "&#38");
    message = message.replaceAll("<", "&lt;");
    message = message.replaceAll(">", "&gt;");
    message = message.replaceAll("\"", "&quot;");
    message = message.replaceAll("\n", "<br/>");
    message = message.replaceAll("\\\\", "&#92");
    message = message.replaceAll("\t", "  ");

    BasicDBObject doc = new BasicDBObject();
    doc.put("user", user);
    doc.put("message", message);
    doc.put("time", new Date());
    doc.put("timestamp", System.currentTimeMillis());
    doc.put("isSystem", isSystem);
    if (options != null) {
        options = options.replaceAll("<", "&lt;");
        options = options.replaceAll(">", "&gt;");
        doc.put("options", options);
    }/*from ww  w .  jav  a  2s  .com*/
    coll.insert(doc);

    this.updateRoomTimestamp(room);
}