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.apache.isis.objectstore.nosql.db.mongo.DemoMongo.java

License:Apache License

public void installed() throws Exception {

    final Mongo m = new Mongo();

    for (final String s : m.getDatabaseNames()) {
        System.out.println(s);/*from  w w w.ja  v a2s . com*/
    }

    /*
     * Mongo m = new Mongo( "localhost" ); Mongo m = new Mongo( "localhost"
     * , 27017 );
     */
    m.dropDatabase("mydb");

    System.out.println("\n...");
    for (final String s : m.getDatabaseNames()) {
        System.out.println(s);
    }

    final DB db = m.getDB("mydb");
    /*
     * DBCollection coll = db.getCollection("testCollection1"); coll =
     * db.getCollection("testCollection2");
     */

    final DBCollection coll = db.getCollection("testCollection1");

    final BasicDBObject doc = new BasicDBObject();

    doc.put("name", "MongoDB");
    doc.put("type", "database");
    doc.put("count", 1);

    final BasicDBObject info = new BasicDBObject();

    info.put("x", 203);
    info.put("y", 102);

    doc.put("info", info);

    coll.insert(doc);

    final Set<String> colls = db.getCollectionNames();

    for (final String s : colls) {
        System.out.println(s);
    }

}

From source file:org.apache.isis.objectstore.nosql.db.mongo.MongoDb.java

License:Apache License

@Override
public void addService(final ObjectSpecId objectSpecId, final String key) {
    final DBCollection services = db.getCollection("services");
    services.insert(new BasicDBObject().append("name", objectSpecId.asString()).append("key", key));
    LOG.info("service added " + objectSpecId + ":" + key);
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.java

License:Apache License

@Override
public <T extends Document> boolean create(Collection<T> collection, List<UpdateOp> updateOps) {
    log("create", updateOps);
    List<T> docs = new ArrayList<T>();
    DBObject[] inserts = new DBObject[updateOps.size()];
    List<String> ids = Lists.newArrayListWithCapacity(updateOps.size());

    for (int i = 0; i < updateOps.size(); i++) {
        inserts[i] = new BasicDBObject();
        UpdateOp update = updateOps.get(i);
        UpdateUtils.assertUnconditional(update);
        T target = collection.newDocument(this);
        UpdateUtils.applyChanges(target, update);
        docs.add(target);/*from  ww w .j a  va2s. c o m*/
        ids.add(updateOps.get(i).getId());
        for (Entry<Key, Operation> entry : update.getChanges().entrySet()) {
            Key k = entry.getKey();
            Operation op = entry.getValue();
            switch (op.type) {
            case SET:
            case MAX:
            case INCREMENT: {
                inserts[i].put(k.toString(), op.value);
                break;
            }
            case SET_MAP_ENTRY: {
                Revision r = k.getRevision();
                if (r == null) {
                    throw new IllegalStateException("SET_MAP_ENTRY must not have null revision");
                }
                DBObject value = (DBObject) inserts[i].get(k.getName());
                if (value == null) {
                    value = new RevisionEntry(r, op.value);
                    inserts[i].put(k.getName(), value);
                } else if (value.keySet().size() == 1) {
                    String key = value.keySet().iterator().next();
                    Object val = value.get(key);
                    value = new BasicDBObject(key, val);
                    value.put(r.toString(), op.value);
                    inserts[i].put(k.getName(), value);
                } else {
                    value.put(r.toString(), op.value);
                }
                break;
            }
            case REMOVE_MAP_ENTRY:
                // nothing to do for new entries
                break;
            }
        }
        if (!inserts[i].containsField(Document.MOD_COUNT)) {
            inserts[i].put(Document.MOD_COUNT, 1L);
            target.put(Document.MOD_COUNT, 1L);
        }
    }

    DBCollection dbCollection = getDBCollection(collection);
    final Stopwatch watch = startWatch();
    boolean insertSuccess = false;
    try {
        try {
            dbCollection.insert(inserts);
            if (collection == Collection.NODES) {
                for (T doc : docs) {
                    nodesCache.putIfAbsent((NodeDocument) doc);
                    updateLocalChanges((NodeDocument) doc);
                }
            }
            insertSuccess = true;
            return true;
        } catch (MongoException e) {
            return false;
        }
    } finally {
        stats.doneCreate(watch.elapsed(TimeUnit.NANOSECONDS), collection, ids, insertSuccess);
    }
}

From source file:org.apache.karaf.jaas.modules.mongo.internal.DefaultUserDetailService.java

License:Apache License

@Override
public UserInfo addUser(UserInfo user) throws Exception {

    DB db = getDB();//from w  w  w  . j  a  va2 s.c o m

    DBCollection users = db.getCollection(configuration.getUserCollectionName());

    DBCollection roles = db.getCollection(configuration.getGroupCollectionName());

    DBObject storedUser = users.findOne(new BasicDBObject().append("username", user.getName()));

    if (storedUser == null) {

        users.insert(BasicDBObjectBuilder.start("username", user.getName())
                .append("passwordHash", user.getPassword()).get());

    } else {
        // will not do anything here
    }

    for (String role : user.getGroups()) {

        DBObject roleQuery = new BasicDBObject("name", role);

        // roles are unique by name
        DBObject roleData = roles.findOne(roleQuery, ROLE_PROJECTION);

        if (roleData == null) {
            // add role with user as first member
            BasicDBList members = new BasicDBList();
            members.add(user.getName());
            roleData = BasicDBObjectBuilder.start().add("name", role).add("members", members).get();

            roles.insert(roleData);

        } else {

            // add user to group if not already in the role's member list
            Object mo = roleData.get("members");
            if (mo == null) {

                // TODO what here?
                BasicDBObject updateObject = new BasicDBObject().append("$push",
                        new BasicDBObject("members", user.getName()));

                roles.update(roleQuery, updateObject);

            } else if (mo != null && mo instanceof List) {

                // if user is in group already we dont need to do anything
                List<?> existingMembers = (List<?>) mo;

                if (!existingMembers.contains(user.getName())) {
                    // push this user to the members list
                    BasicDBObject updateObject = new BasicDBObject().append("$push",
                            new BasicDBObject("members", user.getName()));

                    roles.update(roleQuery, updateObject);

                }

            } else {
                log.warn("The members collection of group [{}] is not a list but of type [{}].", role,
                        mo.getClass().getName());
            }

        }

    }

    return user;
}

From source file:org.apache.rya.mongodb.instance.MongoRyaInstanceDetailsRepository.java

License:Apache License

@Override
public void initialize(final RyaDetails details)
        throws AlreadyInitializedException, RyaDetailsRepositoryException {
    // Preconditions.
    requireNonNull(details);//from w  w w  . j  a v  a  2 s  .com

    if (!details.getRyaInstanceName().equals(instanceName)) {
        throw new RyaDetailsRepositoryException(
                "The instance name that was in the provided 'details' does not match "
                        + "the instance name that this repository is connected to. Make sure you're connected to the"
                        + "correct Rya instance.");
    }

    if (isInitialized()) {
        throw new AlreadyInitializedException(
                "The repository has already been initialized for the Rya instance named '" + instanceName
                        + "'.");
    }

    // Create the document that hosts the details if it has not been created yet.
    final DBCollection col = db.createCollection(INSTANCE_DETAILS_COLLECTION_NAME, new BasicDBObject());

    // Write the details to the collection.
    col.insert(MongoDetailsAdapter.toDBObject(details));
}

From source file:org.axonframework.eventsourcing.eventstore.mongo.AbstractEventStorageStrategy.java

License:Apache License

@Override
public void appendEvents(DBCollection eventCollection, List<? extends EventMessage<?>> events,
        Serializer serializer) throws MongoException.DuplicateKey {
    eventCollection.insert(createEventDocuments(events, serializer).collect(Collectors.toList()));
}

From source file:org.axonframework.eventsourcing.eventstore.mongo.AbstractEventStorageStrategy.java

License:Apache License

@Override
public void appendSnapshot(DBCollection snapshotCollection, DomainEventMessage<?> snapshot,
        Serializer serializer) throws MongoException.DuplicateKey {
    snapshotCollection.insert(createSnapshotDocument(snapshot, serializer));
}

From source file:org.benjp.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;");
        options = options.replaceAll("'", "\"");
        //      options = options.replaceAll("\"", "&quot;");
        //      options = options.replaceAll("\\\\", "&#92");
        doc.put("options", options);
    }//from w ww  .  ja v a 2 s .  co  m

    coll.insert(doc);

    this.updateRoomTimestamp(room);
}

From source file:org.benjp.services.mongodb.ChatServiceImpl.java

License:Open Source License

private void ensureIndexInRoom(String room) {
    DBCollection coll = db().getCollection(M_ROOM_PREFIX + room);
    BasicDBObject doc = new BasicDBObject();
    doc.put("timestamp", System.currentTimeMillis());
    coll.insert(doc);
    ConnectionManager.getInstance().ensureIndexesInRoom(room);
    coll.remove(doc);/*from   w w w. j a v  a 2 s .c  om*/
}

From source file:org.benjp.services.mongodb.ChatServiceImpl.java

License:Open Source License

public String getSpaceRoom(String space) {
    String room = ChatUtils.getRoomId(space);
    DBCollection coll = db().getCollection(M_ROOM_PREFIX + M_ROOMS_COLLECTION);

    BasicDBObject basicDBObject = new BasicDBObject();
    basicDBObject.put("_id", room);

    DBCursor cursor = coll.find(basicDBObject);
    if (!cursor.hasNext()) {
        try {//from  w w w  . ja v a2 s . c  om
            basicDBObject.put("space", space);
            basicDBObject.put("type", TYPE_ROOM_SPACE);
            coll.insert(basicDBObject);
            ensureIndexInRoom(room);
        } catch (MongoException me) {
            log.warning(me.getCode() + " : " + room + " : " + me.getMessage());
        }
    }

    return room;
}