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.github.cherimojava.data.mongo.entity.EntityInvocationHandler.java

License:Apache License

/**
 * stores the given EntityInvocationHandler represented Entity in the given Collection
 *
 * @param handler/*from  ww  w .j av  a2 s.  com*/
 *            EntityInvocationHandler (Entity) to save
 * @param coll
 *            MongoCollection to save entity into
 */
@SuppressWarnings("unchecked")
static <T extends Entity> void save(EntityInvocationHandler handler, MongoCollection<T> coll) {
    for (ParameterProperty cpp : handler.properties.getValidationProperties()) {
        cpp.validate(handler.data.get(cpp.getMongoName()));
    }
    BsonDocumentWrapper wrapper = new BsonDocumentWrapper<>(handler.proxy,
            (org.bson.codecs.Encoder<Entity>) coll.getCodecRegistry().get(handler.properties.getEntityClass()));
    UpdateResult res = coll.updateOne(
            new BsonDocument("_id",
                    BsonDocumentWrapper.asBsonDocument(EntityCodec._obtainId(handler.proxy), idRegistry)),
            new BsonDocument("$set", wrapper), new UpdateOptions());
    if (res.getMatchedCount() == 0) {
        // TODO this seems too nasty, there must be a better way.for now live with it
        coll.insertOne((T) handler.proxy);
    }
    handler.persist();
}

From source file:com.gs.obevo.mongodb.impl.MongoDbChangeAuditDao.java

License:Apache License

@Override
public void insertNewChange(Change change, DeployExecution deployExecution) {
    MongoCollection<Document> auditCollection = getAuditCollection(change);

    auditCollection.insertOne(createDocFromChange(change, deployExecution, null));
}

From source file:com.gs.obevo.mongodb.impl.MongoDbDeployExecutionDao.java

License:Apache License

@Override
public void persistNew(DeployExecution deployExecution, PhysicalSchema physicalSchema) {
    MongoDatabase database = mongoClient.getDatabase(physicalSchema.getPhysicalName());
    MongoCollection<Document> auditCollection = database.getCollection(deployExecutionTableName);

    MutableInt mutableInt = nextIdBySchema.get(physicalSchema);
    mutableInt.increment();//from  www.jav  a 2s  .co m
    ((DeployExecutionImpl) deployExecution).setId(mutableInt.longValue());
    Document doc = getDocumentFromDeployExecution(deployExecution, false);
    auditCollection.insertOne(doc);
}

From source file:com.ibm.research.mongotx.daytrader.Load.java

License:Open Source License

public static Document register(TxDatabase client, Map<String, Document> userId2Account, String userId,
        String password, String fullname, String address, String email, String creditCard, double openBalance,
        double balance) {
    MongoCollection<Document> accounts = client.getDatabase().getCollection(COL_ACCOUNT);
    MongoCollection<Document> accountProfiles = client.getDatabase().getCollection(COL_ACCOUNTPROFILE);

    Document accountData = new Document();

    int accountId = client.incrementAndGetInt(new Document(ATTR_SEQ_KEY, COL_ACCOUNT));
    long creationDate = System.currentTimeMillis();
    long lastLogin = creationDate;
    int loginCount = 0;
    int logoutCount = 0;

    accountData.put("_id", accountId);
    accountData.put(A_ACCOUNTID, accountId);
    accountData.put(A_CREATIONDATE, creationDate);
    accountData.put(A_OPENBALANCE, openBalance);
    accountData.put(A_BALANCE, balance);
    accountData.put(A_LASTLOGIN, lastLogin);
    accountData.put(A_LOGINCOUNT, loginCount);
    accountData.put(A_LOGOUTCOUNT, logoutCount);
    accountData.put(A_PROFILE_USERID, userId);

    accounts.insertOne(accountData);

    Document accountProfile = new Document();
    accountProfile.put("_id", userId);
    accountProfile.put(AP_USERID, userId);
    accountProfile.put(AP_PASSWD, password);
    accountProfile.put(AP_FULLNAME, fullname);
    accountProfile.put(AP_ADRRESS, address);
    accountProfile.put(AP_EMAIL, email);
    accountProfile.put(AP_CREDITCARD, creditCard);
    accountProfiles.insertOne(accountProfile);

    userId2Account.put(userId, accountData);

    return accountData;
}

From source file:com.ibm.research.mongotx.daytrader.Load.java

License:Open Source License

public static Document createQuote(TxDatabase client, String symbol, String companyName, double price)
        throws Exception {
    MongoCollection<Document> quotes = client.getDatabase().getCollection(COL_QUOTE);

    Document quoteData = new Document();
    double volume = 0.0, change = 0.0;

    quoteData.put("_id", symbol);
    quoteData.put(Q_SYMBOL, symbol); // symbol
    quoteData.put(Q_COMPANYNAME, companyName); // companyName
    quoteData.put(Q_VOLUME, volume); // volume
    quoteData.put(Q_PRICE, price); // price
    quoteData.put(Q_OPEN1, price); // open
    quoteData.put(Q_LOW, price); // low
    quoteData.put(Q_HIGH, price); // high
    quoteData.put(Q_CHANGE1, change); // change

    quotes.insertOne(quoteData);

    return quoteData;
}

From source file:com.imaginea.mongodb.services.impl.CollectionServiceImpl.java

License:Apache License

/**
 * Deletes a collection inside a database in mongo to which user is connected to.
 *
 * @param dbName Name of Database in which to insert a collection
 * @param collectionName Name of Collection to be inserted
 * @return Success if deletion is successful else throw exception
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException
 * @throws CollectionException throw super type of
 *         UndefinedCollectionException,DeleteCollectionException
 *///w  w  w . j  a v a  2s  .  c o m

private void createCollection(CreateCollectionOptions options, MongoCollection<Document> selectedCollection,
        String selectedCollectionName, MongoDatabase db) {
    db.createCollection(selectedCollectionName + "_temp", options);
    MongoCollection<Document> tempCollection = db.getCollection(selectedCollectionName + "_temp");

    MongoCursor<Document> cur = selectedCollection.find().iterator();
    while (cur.hasNext()) {
        Document obj = cur.next();
        tempCollection.insertOne(obj);
    }
    MongoNamespace namespace = selectedCollection.getNamespace();
    selectedCollection.drop();
    tempCollection.renameCollection(namespace);
}

From source file:com.inflight.rest.AddFlightService.java

@SuppressWarnings("resource")
@POST/*from   www .j  a va 2s.  com*/
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String signup(@FormParam("username") String username, @FormParam("confirmCode") String confirmCode,
        @FormParam("fromLocation") String fromLocation, @FormParam("toLocation") String toLocation)
        throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("location");

    Document doc = collection.find(or(eq("confirmCode", confirmCode), eq("toLocation", toLocation))).first();
    if (doc == null) {
        Document newDoc = new Document("username", username).append("confirmCode", confirmCode)
                .append("fromLocation", fromLocation).append("toLocation", toLocation);

        collection.insertOne(newDoc);
        result = "{\"success\": true}";
        return result;
    } else {
        result = "{\"success\": false, \"message\": \"Booking Reference or To Location already exists\"}";
        return result;
    }
}

From source file:com.inflight.rest.SignUpService.java

@SuppressWarnings("resource")
@POST//from  w w w.ja v  a 2 s . c o m
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String signup(@FormParam("username") String username, @FormParam("password") String password,
        @FormParam("email") String email) throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("users");

    Document doc = collection.find(or(eq("username", username), eq("email", email))).first();
    if (doc == null) {
        Document newDoc = new Document("username", username)
                .append("password", Password.getSaltedHash(password)).append("email", email);

        collection.insertOne(newDoc);
        result = "{\"success\": true}";
        return result;
    } else {
        result = "{\"success\": false, \"message\": \"Username or Email already exists\"}";
        return result;
    }

}

From source file:com.modelo.mequipo.java

public boolean add() {
    try {//from   www . jav  a  2  s . c o m
        MongoCollection collection = this.getCollection("equipo");
        collection.insertOne(this.toEquipo());
        return true;
    } catch (MongoException e) {
        System.out.println("com.modelo.mequipo.add()");
        return false;
    }

}

From source file:com.mycompany.mavenproject2.AddCatController.java

public void InsertMongo() {
    client = new MongoClient();
    db = client.getDatabase("FinalDemo");
    MongoCollection col = db.getCollection("CategoryDetail");
    final Document seedData = createSeedData();
    col.insertOne(seedData);

    LocalName.clear();//from   w  w  w  .j a v  a2  s .  co  m
    CatName.clear();
}