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:com.shampan.model.UserModel.java

public ResultEvent registration(UserDAO userInfo) {
    try {//from  w ww . ja va2 s  . c o  m
        MongoCollection<UserDAO> mongoCollection = DBConnection.getInstance().getConnection()
                .getCollection(Collections.USERS.toString(), UserDAO.class);
        if (userInfo != null) {
            userInfo.setCreatedOn(utility.getCurrentTime());
            userInfo.setLastLogin(utility.getCurrentTime());
            mongoCollection.insertOne(userInfo);
            this.getResultEvent().setResponseCode(PropertyProvider.get("SUCCESSFUL_OPERATION"));
        } else {
            this.getResultEvent().setResponseCode(PropertyProvider.get("NULL_POINTER_EXCEPTION"));
        }
    } catch (Exception ex) {
        this.getResultEvent().setResponseCode(PropertyProvider.get("ERROR_EXCEPTION"));
    }
    return this.resultEvent;
}

From source file:com.shampan.model.VideoModel.java

/**
 * This method will add video category//w  ww.  j  a  va2s  . com
 *
 * @param categoryInfo category information
 * @author created by Rashida on 21 October
 */
public String addVideoCategory(String categoryInfo) {
    MongoCollection<VideoCategoryDAO> mongoCollection = DBConnection.getInstance().getConnection()
            .getCollection(Collections.VIDEOCATEGORIES.toString(), VideoCategoryDAO.class);
    VideoCategoryDAO category = new VideoCategoryDAOBuilder().build(categoryInfo);
    if (category != null) {
        mongoCollection.insertOne(category);
        resultEvent.setResponseCode(PropertyProvider.get("Created"));
        return resultEvent.toString();
    } else {
        resultEvent.setResponseCode(PropertyProvider.get("BadRequest"));
        return resultEvent.toString();

    }
}

From source file:com.shampan.model.VideoModel.java

/**
 * This method will add video/*from  w w  w  . java 2  s.c  o m*/
 *
 * @param videoInfo video information
 * @author created by Rashida on 21 October
 */
public String addVideo(String videoInfo) {
    MongoCollection<VideoDAO> mongoCollection = DBConnection.getInstance().getConnection()
            .getCollection(Collections.VIDEOS.toString(), VideoDAO.class);
    VideoDAO vedio = new VideoDAOBuilder().build(videoInfo);
    if (vedio != null) {
        mongoCollection.insertOne(vedio);
        resultEvent.setResponseCode(PropertyProvider.get("Created"));
        return resultEvent.toString();
    } else {
        resultEvent.setResponseCode(PropertyProvider.get("BadRequest"));
        return resultEvent.toString();

    }
}

From source file:com.shiyq.mongodb.InsertThread.java

@Override
public void run() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase mongoDatabase = mongoClient.getDatabase("study");

    MongoCollection<Document> collection = mongoDatabase.getCollection("s_user");
    Document document;/*from  www. java2 s .  co  m*/
    while (true) {
        document = new Document();
        document.append("code", code);
        document.append("name", name);
        document.append("password", password);
        document.append("create_date", new Date());

        collection.insertOne(document);
    }
}

From source file:com.sitewhere.event.persistence.mongodb.MongoDeviceEventManagementPersistence.java

License:Open Source License

/**
 * Insert an event, taking into account whether the device management
 * implementation in configured for bulk operations.
 * //from   w ww. ja v a 2s . c om
 * @param collection
 * @param object
 * @param bulk
 * @param buffer
 * @throws SiteWhereException
 */
public static void insertEvent(MongoCollection<Document> collection, Document object, boolean bulk,
        IDeviceEventBuffer buffer) throws SiteWhereException {
    try {
        if (bulk) {
            buffer.add(object);
        } else {
            collection.insertOne(object);
        }
    } catch (MongoCommandException e) {
        throw new SiteWhereException("Error during MongoDB insert.", e);
    } catch (MongoTimeoutException e) {
        throw new SiteWhereException("Connection to MongoDB lost.", e);
    }
}

From source file:com.spleefleague.bungee.io.EntityBuilder.java

public static <T extends DBEntity & DBSaveable> void save(T object, MongoCollection<Document> dbcoll,
        boolean override) {
    DBEntity dbe = (DBEntity) object;/*from  w  w  w  .  j a v a 2s. co  m*/
    ObjectId _id = dbe.getObjectId();
    Document index = null;
    if (override && _id != null) {
        index = new Document("_id", _id);
    }
    Document dbo = serialize(object);
    validate(dbo);
    if (index != null) {
        dbcoll.updateOne(index, dbo);
    } else {
        dbo = (Document) dbo.get("$set");
        dbcoll.insertOne(dbo);
        _id = (ObjectId) dbcoll.find(dbo).first().get("_id");
        try {
            Field _idField = DBEntity.class.getDeclaredField("_id");
            _idField.setAccessible(true);
            _idField.set(dbe, _id);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.spleefleague.core.io.EntityBuilder.java

public static <T extends DBEntity & DBSaveable> void save(T object, MongoCollection<Document> dbcoll,
        boolean override) {
    if (object == null) {
        return;//from w w w  .jav  a2 s  .  c om
    }
    DBEntity dbe = (DBEntity) object;
    ObjectId _id = dbe.getObjectId();
    Document index = null;
    if (override && _id != null) {
        index = new Document("_id", _id);
    }
    Document dbo = serialize(object);
    validate(dbo);
    if (index != null) {
        dbcoll.updateOne(index, dbo);
    } else {
        dbo = (Document) dbo.get("$set");
        dbcoll.insertOne(dbo);
        _id = (ObjectId) dbcoll.find(dbo).first().get("_id");
        try {
            Field _idField = DBEntity.class.getDeclaredField("_id");
            _idField.setAccessible(true);
            _idField.set(dbe, _id);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Inserts a new document in the given raw collection within the given database (row-like mode).
 * @param dbName//from   w  w  w .ja  v  a 2s .com
 * @param collectionName
 * @param recvTimeTs
 * @param recvTime
 * @param entityId
 * @param entityType
 * @param attrName
 * @param attrType
 * @param attrValue
 * @param attrMd
 * @throws Exception
 */
public void insertContextDataRaw(String dbName, String collectionName, long recvTimeTs, String recvTime,
        String entityId, String entityType, String attrName, String attrType, String attrValue, String attrMd)
        throws Exception {
    MongoDatabase db = getDatabase(dbName);
    MongoCollection collection = db.getCollection(collectionName);
    Document doc = new Document("recvTime", new Date(recvTimeTs * 1000));

    switch (dataModel) {
    case COLLECTIONPERSERVICEPATH:
        doc.append("entityId", entityId).append("entityType", entityType).append("attrName", attrName)
                .append("attrType", attrType).append("attrValue", attrValue);
        break;
    case COLLECTIONPERENTITY:
        doc.append("attrName", attrName).append("attrType", attrType).append("attrValue", attrValue);
        break;
    case COLLECTIONPERATTRIBUTE:
        doc.append("attrType", attrType).append("attrValue", attrValue);
        break;
    default:
        // this will never be reached
    } // switch

    LOGGER.debug("Inserting data=" + doc.toString() + " within collection=" + collectionName);
    collection.insertOne(doc);
}

From source file:com.torodb.testing.mongodb.docker.ReplicaSetContract.java

License:Apache License

@Test
default void genericTest() {
    int docsToInsert = 100;

    try (ReplicaSet replicaSet = getReplicaSet(simpleReplConfig())) {
        replicaSet.startAsync();// ww  w. j a va2  s . c om
        replicaSet.awaitRunning();

        getLogger().debug("Inserting {} documents on {}", docsToInsert, replicaSet.getReplSetName());
        MongoDatabase db = replicaSet.getClient().getDatabase("testDb");
        MongoCollection<Document> col = db.getCollection("testCol")
                .withWriteConcern(replicaSet.getTotalWriteConcern());
        for (int i = 0; i < docsToInsert; i++) {
            col.insertOne(new Document());
        }

        Assertions.assertEquals(docsToInsert, col.count());

        for (ReplMongod mongo : replicaSet.getMongos()) {
            getLogger().debug("Assertions on node {}", mongo);

            long oplogCount = mongo.getMongoClient().getDatabase("local").getCollection("rs.oplog").count();

            Assertions.assertNotEquals(0, oplogCount, "Oplog on node " + mongo + " is empty");

            long colCount = mongo.getMongoClient().getDatabase("testDb").getCollection("testCol").count();

            Assertions.assertEquals(docsToInsert, colCount, "Incorrect number of documents replicated");
        }
    }
}

From source file:com.torodb.testing.mongodb.docker.ShardedClusterContract.java

License:Apache License

@Test
default void startAndStop() {

    try (ShardedCluster cluster = getShardedCluster(smallShardedClusterConfig())) {
        getLogger().debug("Starting cluster...");
        cluster.startAsync();//ww w .j  a va2s. c  o m
        cluster.awaitRunning();

        getLogger().debug("Cluster has been started");
        getLogger().debug("Configuring cluster");

        cluster.enableSharding("testDb");
        cluster.shardCollection("testDb", "testCol");
        cluster.setChunckSize(1);

        getLogger().debug("Sharding has been configured");

        getLogger().debug("Inserting documents");

        int docsToInsert = 10_000;

        MongoDatabase db = cluster.getClient().getDatabase("testDb");
        MongoCollection<Document> col = db.getCollection("testCol");
        for (int i = 0; i < docsToInsert; i++) {
            col.insertOne(new Document());
        }

        getLogger().debug("Documents have been inserted");

        Assertions.assertEquals(docsToInsert, col.count());
    }
}