Java Code Examples for com.mongodb.DBCollection#insert()

The following examples show how to use com.mongodb.DBCollection#insert() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InitialSetupMigration.java    From spring-boot-completablefuture with MIT License 7 votes vote down vote up
@ChangeSet(order = "01",
           author = "developer",
           id = "01-addUsers")
public void addUsers(final DB db) {
    final DBCollection userCollection = db.getCollection(User.COLLECTION_NAME);

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c3f"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "One")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c40"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "Two")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());
}
 
Example 2
Source File: MongoDBUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 *  Save i.e. INSERT or UPDATE an object to mongodb.
 *  
 * @param query usually the _id of collection, which is byte[] , null means insert a new row
 * @param objectToSave the object to save
 * @param databaseName the database
 * @param namespace the namespace, maybe null
 * @param isSafeWrite whether to enable the SafeWrite mode
 */
public static final void saveToMongo(DBObject query, DBObject objectToSave, 
		String databaseName, String namespace, String collection, boolean isSafeWrite) {

	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	if ( isSafeWrite ) {
		if ( query == null ) {
			coll.insert(objectToSave);
		} else {
			coll.update(query, objectToSave, true, false, WriteConcern.SAFE);
		}
	} else {
		if ( query == null ) {
			coll.insert(objectToSave);
		} else {
			coll.update(query, objectToSave, true, false, WriteConcern.NONE);
		}
	}
}
 
Example 3
Source File: ExecutionApp.java    From android-kubernetes-blockchain with Apache License 2.0 6 votes vote down vote up
private static void executeRequest(String data, MongoClient mongo) {
	String body;
	try {
		body = Task.post(executionURL, data);
		JsonObject jsonObj = new JsonParser().parse(body).getAsJsonObject();
		if (jsonObj.get("status").toString().equals("\"success\"")) {
			DB database = mongo.getDB(dbName);
			DBCollection collection = Task.getDBCollection(database, "results");
			List<DBObject> list = new ArrayList<>();
			BasicDBObject dataObject = new BasicDBObject();
			dataObject.append("resultId", jsonObj.get("resultId").getAsString());
			dataObject.append("query", data);
			list.add(dataObject);
			collection.insert(list);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 4
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
public void testFindOne() throws UnknownHostException {
  MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
  DBCollection collection = client.getCollection("marc");
  BasicDBObject doc = createTestObject();
  collection.insert(doc);
  assertEquals(1, collection.count());
  DBObject myDoc = collection.findOne();
  assertEquals("MongoDB", myDoc.get("name"));
  assertEquals("database", myDoc.get("type"));
  assertEquals(1, myDoc.get("count"));
  assertEquals(BasicDBObject.class, myDoc.get("info").getClass());
  assertEquals(new BasicDBObject("x", 203).append("y", 102), myDoc.get("info"));
  assertEquals(203, ((BasicDBObject)myDoc.get("info")).get("x"));
  assertEquals(Integer.class, ((BasicDBObject)myDoc.get("info")).get("x").getClass());
  System.out.println(myDoc);
  collection.remove(new BasicDBObject("name", "MongoDB"));
}
 
Example 5
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 6 votes vote down vote up
public synchronized void testImport() throws URISyntaxException, IOException, InterruptedException {
  MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
  DBCollection collection = client.getCollection("marc");
  assertEquals(0, collection.count());
  boolean insert = true;
  if (insert) {
    JsonPathCache<? extends XmlFieldInstance> cache;
    List<String> records = FileUtils.readLines("general/marc.json");
    for (String record : records) {
      cache = new JsonPathCache<>(record);
      Object jsonObject = jsonProvider.parse(record);
      String id   = cache.get("$.controlfield.[?(@.tag == '001')].content").get(0).getValue();
      String x003 = cache.get("$.controlfield.[?(@.tag == '003')].content").get(0).getValue();

      BasicDBObject doc = new BasicDBObject("type", "marcjson")
        .append("id", id)
        .append("x003", x003)
        .append("record", record);
      collection.insert(doc);
    }
    assertEquals(674, collection.count());
  }
  collection.remove(new BasicDBObject("type", "marcjson"));
  assertEquals(0, collection.count());
}
 
Example 6
Source File: SparkCache.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public synchronized void putSpark(String sparkId, byte[] img) {
//		sparkMap.put(sparkId, img);
		Mongo mongo;
		try {
			mongo = Configuration.getInstance().getMongoConnection();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return;
		}
		DB db = mongo.getDB("scava");
		DBCollection col = db.getCollection("sparks");
		
		BasicDBObject obj = new BasicDBObject();
		obj.put("sparkid", sparkId);
		obj.put("bytes", img);
		obj.put("created_at", new Date());
		
		col.insert(obj);
	}
 
Example 7
Source File: RawStorageInterceptor.java    From hvdf with Apache License 2.0 6 votes vote down vote up
public void pushSample(DBObject sample, boolean isList, BasicDBList resultList) {
	
	if(isList){
		
		// Use the batch API to send a number of samples
		storeBatch((BasicDBList)sample, resultList);			
	}
	else if(sample != null){
		
		// Create an oid to embed the sample time
		BasicDBObject doc = ((BasicDBObject) sample);
		SampleId _id = this.idFactory.createId(sample);
		sample.put(Sample.ID_KEY, _id.toObject());
		resultList.add(_id.toObject());

		// Get the correct slice from the allocator and insert
		long timestamp = doc.getLong(Sample.TS_KEY);
		DBCollection collection = collectionAllocator.getCollection(timestamp);
		collection.insert(doc);
	}
}
 
Example 8
Source File: ServerIntegrationTest.java    From dropwizard-mongo with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    final DB test = mongoClient.getDB("test");
    final DBCollection coll = test.getCollection("test");
    coll.remove(new BasicDBObject());

    coll.insert(new BasicDBObject());
    coll.insert(new BasicDBObject());

}
 
Example 9
Source File: MongoDBTestHelper.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Inserts a new object with { key: value } at given server.
 * @return The new document's id
 */
public static String insert(AbstractMongoDBServer entity, String key, Object value) {
    LOG.info("Inserting {}:{} at {}", new Object[]{key, value, entity});
    MongoClient mongoClient = clientForServer(entity);
    try {
        DB db = mongoClient.getDB(TEST_DB);
        DBCollection testCollection = db.getCollection(TEST_COLLECTION);
        BasicDBObject doc = new BasicDBObject(key, value);
        testCollection.insert(doc);
        ObjectId id = (ObjectId) doc.get("_id");
        return id.toString();
    } finally {
        mongoClient.close();
    }
}
 
Example 10
Source File: AdminUtils.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/delete/{product}/{version}")
@Produces(MediaType.APPLICATION_JSON)
public Response softDeleteSingleVersion(@PathParam("product") final String product,
		@PathParam("version") final String version) {

	final DBCollection collection = this.mongoLegacyDb.getCollection("summary");
	final DBCollection targetCollection = this.mongoLegacyDb.getCollection("deletedSummary");

	final Pattern productReg = java.util.regex.Pattern.compile("^" + product + "/" + version + "$");
	final BasicDBObject query = new BasicDBObject("_id", productReg);

	final DBCursor cursor = collection.find(query);
	DBObject doc;

	while (cursor.hasNext()) {
		doc = cursor.next();
		// kill the old id
		doc.removeField("_id");
		try {
			targetCollection.insert(doc);
		} catch (final Throwable e) {
			return Response.status(500).build();
		}
	}

	collection.remove(query);

	return Response.ok().build();
}
 
Example 11
Source File: AdminUtils.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@DELETE
@Path("/delete/{product}")
@Produces(MediaType.APPLICATION_JSON)
public Response softDeleteEntireProduct(@PathParam("product") final String product) {

	final DBCollection collection = this.mongoLegacyDb.getCollection("summary");
	final DBCollection targetCollection = this.mongoLegacyDb.getCollection("deletedSummary");

	final BasicDBObject query = new BasicDBObject("coordinates.product", product);

	final DBCursor cursor = collection.find(query);
	DBObject doc;

	while (cursor.hasNext()) {
		doc = cursor.next();
		// kill the old id
		doc.removeField("_id");
		try {
			targetCollection.insert(doc);
		} catch (final Throwable e) {
			return Response.status(500).build();
		}
	}

	collection.remove(query);

	return Response.ok().build();
}
 
Example 12
Source File: RootController.java    From hcp-cloud-foundry-tutorials with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody Result onRootAccess() {

    DBCollection collection = mongoTemplate.getCollection("test");
    long count = collection.getCount();
    log.info("Object count in 'test' collection before insert: " + count + "<br/> Inserting one object.<br/>");

    BasicDBObject dBObject = new BasicDBObject();
    dBObject.put("hello", "world");
    collection.insert(dBObject);
    count = collection.count();
    log.info("Object count in test collection after insert:" + count);

    Result result = new Result();
    List<DBObject> dbObjects = new ArrayList<DBObject>();
    DBCursor cursor = collection.find();
    while (cursor.hasNext()) {
        com.mongodb.DBObject obj = cursor.next();
        final String value = (String) obj.get("hello");
        DBObject object = new DBObject();
        object.setKey("hello");
        object.setValue(value);
        dbObjects.add(object);
    }
    result.setDbObjects(dbObjects);
    result.setStatus(
            "Successfully accessed Mongodb service. Retrieving the data object inserted in test collection.");
    collection.drop();
    return result;
}
 
Example 13
Source File: PrivateStorageRepository.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
public void save(String collectionName, Map<String, Object> collectionContent) {
	checkCollection(collectionName);

       final BasicDBObject[] document = {new BasicDBObject()};

	collectionContent.entrySet().stream()
               .forEach(entry -> {
                       document[0] = document[0].append(entry.getKey(), entry.getValue());
               });
       document[0].removeField("_class");

	DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
	collection.insert(document[0]);
}
 
Example 14
Source File: InsertVo.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
public Object insert(DBCollection collection, WriteConcern writeConcern) {
	DBObject document = new BasicDBObject();
	// 匹配_id
	for (int i = 0, n = columns.size(); i < n; i++) {
		// document.put(columns.get(i), values.get(i).getValue());

		String tempColumn = columns.get(i);
		if (3 == tempColumn.length() && tempColumn.equals("_id")) {
			document.put(tempColumn, new ObjectId(values.get(i).getValue().toString()));
		} else {
			document.put(tempColumn, values.get(i).getValue());
		}
	}
	log(document);
	// TODO: WriteConcern.ACKNOWLEDGED需要可以配置
	// WriteResult result = collection.insert(document, WriteConcern.ACKNOWLEDGED);
	// collection.insert(document, MongoComponent.getInstance().getDefaultWriteConcern());
	collection.insert(document, writeConcern);
	Object oid = document.get("_id");
	if (null != oid) {
		return oid.toString();
	}
	return null;
}
 
Example 15
Source File: MarcMongodbClientTest.java    From metadata-qa-marc with GNU General Public License v3.0 5 votes vote down vote up
public void testInsert() throws UnknownHostException {
  MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
  DBCollection collection = client.getCollection("marc");
  BasicDBObject doc = createTestObject();
  collection.insert(doc);
  assertNotNull(collection);
  assertEquals(1, collection.count());
  collection.remove(new BasicDBObject("name", "MongoDB"));
  assertEquals(0, collection.count());
}
 
Example 16
Source File: TestMongoJavaConfig.java    From Spring with Apache License 2.0 4 votes vote down vote up
@Test
public void testInsertViaMongoDbFactory(){
    final DB db = mongoDbFactory.getDb();
    final DBCollection collection = db.getCollection("book");
    collection.insert(new BasicDBObject().append("title", "Harry Potter"));
}
 
Example 17
Source File: MongoDataLoadRule.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            if (Jenkins.getInstance() == null
                || SetupConfig.get().getInjector() == null
                || SetupConfig.get().getInjector().getInstance(Datastore.class) == null) {
                throw new IllegalStateException("Requires configured Jenkins and Mongo configurations");
            }

            DB db = SetupConfig.get().getInjector().getInstance(Datastore.class).getDB();

            //Load mongo data
            File homedir = Jenkins.getInstance().getRootDir();

            for (File fileOfData : homedir.listFiles()) {
                if (!fileOfData.getName().endsWith(".json")) continue;

                String collectionName = fileOfData.getName().replaceAll("\\.json$", "");
                DBCollection collection = db.createCollection(collectionName, new BasicDBObject());

                String data = FileUtils.readFileToString(fileOfData);
                Object bsonObject = JSON.parse(data);
                if (bsonObject instanceof BasicDBList) {
                    BasicDBList basicDBList = (BasicDBList) bsonObject;
                    collection.insert(basicDBList.toArray(new DBObject[0]));
                } else {
                    collection.insert((DBObject) bsonObject);
                }

            }

            for (OrganizationContainer container : Jenkins.getInstance().getAllItems(OrganizationContainer.class)) {
                container.reloadItems();
            }

            base.evaluate();

            // Clean up mongo data
            for (String collectioName : db.getCollectionNames()) {
                db.getCollection(collectioName).drop();
            }
        }
    };
}
 
Example 18
Source File: MongoExample.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB database = mongoClient.getDB("myMongoDb");

        // print existing databases
        mongoClient.getDatabaseNames().forEach(System.out::println);

        database.createCollection("customers", null);

        // print all collections in customers database
        database.getCollectionNames().forEach(System.out::println);

        // create data
        DBCollection collection = database.getCollection("customers");
        BasicDBObject document = new BasicDBObject();
        document.put("name", "Shubham");
        document.put("company", "Baeldung");
        collection.insert(document);

        // update data
        BasicDBObject query = new BasicDBObject();
        query.put("name", "Shubham");
        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("name", "John");
        BasicDBObject updateObject = new BasicDBObject();
        updateObject.put("$set", newDocument);
        collection.update(query, updateObject);

        // read data
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", "John");
        DBCursor cursor = collection.find(searchQuery);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }

        // delete data
        BasicDBObject deleteQuery = new BasicDBObject();
        deleteQuery.put("name", "John");
        collection.remove(deleteQuery);
    }
 
Example 19
Source File: TenantLogRepository.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
public void insert(String domainName, long timestampMillis, String level, String message) {

		String collectionName = domainName;

		checkCollection(collectionName);

		DBObject object = new BasicDBObject();
		object.put("time", timestampMillis);
		object.put("level", level);
		object.put("message", message);
		object.removeField("_class");

		DBCollection collection = mongoAuditTemplate.getCollection(collectionName);
		collection.insert(object);

	}
 
Example 20
Source File: TestMongoXMLConfig.java    From Spring with Apache License 2.0 4 votes vote down vote up
@Test
public void testInsertViaMongoDbFactory(){
    final DB db = mongoDbFactory.getDb();
    final DBCollection collection = db.getCollection("book");
    collection.insert(new BasicDBObject().append("title", "Harry Potter"));
}