Java Code Examples for com.mongodb.client.MongoCollection#insertOne()

The following examples show how to use com.mongodb.client.MongoCollection#insertOne() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: presto   File: MongoSession.java    License: Apache License 2.0 6 votes vote down vote up
private void createTableMetadata(SchemaTableName schemaTableName, List<MongoColumnHandle> columns)
        throws TableNotFoundException
{
    String schemaName = schemaTableName.getSchemaName();
    String tableName = schemaTableName.getTableName();

    MongoDatabase db = client.getDatabase(schemaName);
    Document metadata = new Document(TABLE_NAME_KEY, tableName);

    ArrayList<Document> fields = new ArrayList<>();
    if (!columns.stream().anyMatch(c -> c.getName().equals("_id"))) {
        fields.add(new MongoColumnHandle("_id", OBJECT_ID, true).getDocument());
    }

    fields.addAll(columns.stream()
            .map(MongoColumnHandle::getDocument)
            .collect(toList()));

    metadata.append(FIELDS_KEY, fields);

    MongoCollection<Document> schema = db.getCollection(schemaCollection);
    schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true));
    schema.insertOne(metadata);
}
 
Example 2
Source Project: SI   File: ResourceDAO.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void createDocument(HashMap<String, Object> map) {

		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);

		Document doc = new Document();

		Iterator<String> keys = map.keySet().iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			Object val = map.get(key);
			doc.append(key, val);
		}

		collection.insertOne(doc);

	}
 
Example 3
Source Project: epcis   File: NamedQueryRegistration.java    License: Apache License 2.0 6 votes vote down vote up
private boolean addNamedEventQueryToDB(String name, String description, PollParameters p) {
	MongoCollection<BsonDocument> namedEventQueryCollection = Configuration.mongoDatabase.getCollection("NamedEventQuery",
			BsonDocument.class);
	MongoCollection<BsonDocument> eventDataCollection = Configuration.mongoDatabase.getCollection("EventData",
			BsonDocument.class);
	
	BsonDocument existingDoc = namedEventQueryCollection.find(new BsonDocument("name", new BsonString(name))).first();

	if (existingDoc == null) {
		BsonDocument bson = PollParameters.asBsonDocument(p);
		bson.put("name", new BsonString(name));
		bson.put("description", new BsonString(description));
		namedEventQueryCollection.insertOne(bson);
	} else {
		return false;
	}

	// Create Index with the given NamedEventQuery name and background option
	IndexOptions indexOptions = new IndexOptions().name(name).background(true);
	BsonDocument indexDocument = makeIndexObject(p);
	eventDataCollection.createIndex(indexDocument, indexOptions);
	
	Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is added to DB. ");
	return true;
}
 
Example 4
Source Project: XBDD   File: StatsDao.java    License: Apache License 2.0 6 votes vote down vote up
public void updateStatsForFeatures(final Coordinates coordinates, final List<XbddFeature> features) {
	final MongoCollection<Stats> statsCollection = getStatsCollection();

	// product and version are redundant for search, but ensure they're populated if the upsert results in an insert.
	final String id = coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates.getBuild();
	statsCollection.deleteOne(Filters.eq(id));

	final Stats newStats = new Stats();
	newStats.setCoordinates(CoordinatesMapper.mapCoordinates(coordinates));
	newStats.setId(id);
	newStats.setSummary(getNewStatsSummary());

	for (final XbddFeature xbddFeature : features) {
		if (xbddFeature.getElements() != null) {
			for (final XbddScenario scenario : xbddFeature.getElements()) {
				final List<String> stepStatuses = FeatureMapper.getStepStatusStream(scenario).collect(Collectors.toList());
				final String status = StatusHelper.reduceStatuses(stepStatuses).getTextName();
				newStats.getSummary().replace(status, newStats.getSummary().get(status) + 1);
			}
		}
	}
	statsCollection.insertOne(newStats);
}
 
Example 5
Source Project: mongo-mapper   File: MongoMapperIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBasicMapping() {
    MongoCollection<TestEntity> collection = db.getCollection("test", TestEntity.class);
    collection.drop();

    TestEntity entity = new TestEntity();
    entity.setChecked(true);
    entity.setName("name");
    entity.setI(2);
    entity.setJ(1);

    collection.insertOne(entity);

    TestEntity returned = collection.find().first();
    Assert.assertEquals(entity.isChecked(), returned.isChecked());
    Assert.assertEquals(entity.getName(), returned.getName());
    Assert.assertEquals(entity.getI(), returned.getI());
    Assert.assertEquals(entity.getJ(), returned.getJ());
}
 
Example 6
Source Project: mongo-mapper   File: MongoMapperIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMoreFields() throws Exception {
    MongoCollection<TestEntity> collection = db.getCollection("test_morefields", TestEntity.class);
    collection.drop();

    TestEntity entity = new TestEntity();
    entity.setName("a");
    entity.setChecked(true);
    entity.setJ(2);
    collection.insertOne(entity);

    MongoCollection<TestEntityRef> collection2 = db.getCollection("test_morefields", TestEntityRef.class);
    TestEntityRef returned = collection2.find().first();

    Assert.assertEquals(entity.getName(), returned.getName());
    Assert.assertEquals(entity.getId(), returned.getId());
}
 
Example 7
Source Project: mongo-mapper   File: MongoMapperIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEmbedded() throws Exception {
    MongoCollection<TestEntityWithEmbedded> collection = db.getCollection("test_embedded", TestEntityWithEmbedded.class);
    collection.drop();

    TestEntityEmbedded embedded = new TestEntityEmbedded();
    embedded.setAge(1);
    embedded.setName("testing");

    TestEntityWithEmbedded entity = new TestEntityWithEmbedded();
    entity.setName("embedded");
    entity.setEmbedded(embedded);

    collection.insertOne(entity);

    TestEntityWithEmbedded returned = collection.find().first();
    Assert.assertEquals(entity.getEmbedded(), returned.getEmbedded());
    Assert.assertEquals(entity.getName(), returned.getName());
}
 
Example 8
Source Project: calcite   File: MongoAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void setUp() throws Exception {
  MongoDatabase database = POLICY.database();

  populate(database.getCollection("zips"), MongoAdapterTest.class.getResource("/zips-mini.json"));
  populate(database.getCollection("store"), FoodmartJson.class.getResource("/store.json"));
  populate(database.getCollection("warehouse"),
      FoodmartJson.class.getResource("/warehouse.json"));

  // Manually insert data for data-time test.
  MongoCollection<BsonDocument> datatypes =  database.getCollection("datatypes")
      .withDocumentClass(BsonDocument.class);
  if (datatypes.countDocuments() > 0) {
    datatypes.deleteMany(new BsonDocument());
  }

  BsonDocument doc = new BsonDocument();
  Instant instant = LocalDate.of(2012, 9, 5).atStartOfDay(ZoneOffset.UTC).toInstant();
  doc.put("date", new BsonDateTime(instant.toEpochMilli()));
  doc.put("value", new BsonInt32(1231));
  doc.put("ownerId", new BsonString("531e7789e4b0853ddb861313"));
  datatypes.insertOne(doc);

  schema = new MongoSchema(database);
}
 
Example 9
Source Project: game-server   File: MongoTest.java    License: MIT License 6 votes vote down vote up
@Ignore
@Test
public void testInsert() {
    MongoClientURI connectionString = new MongoClientURI("mongodb://127.0.0.1");
    MongoClient mongoClient = new MongoClient(connectionString);

    MongoDatabase database = mongoClient.getDatabase("lztb_att");
    MongoCollection<Document> collection = database.getCollection("test");
    Document doc = new Document("name", "MongoDB")
            .append("type", "database")
            .append("count", 1)
            .append("info", new Document("x", 203).append("y", 102));
    new Document().append("1", 1);
    collection.insertOne(doc);
    mongoClient.close();
}
 
Example 10
public cfData execute( cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
	MongoDatabase db = getMongoDatabase( _session, argStruct );

	String collection = getNamedStringParam( argStruct, "collection", null );
	if ( collection == null )
		throwException( _session, "please specify a collection" );

	cfData data = getNamedParam( argStruct, "data", null );
	if ( data == null )
		throwException( _session, "please specify data to save" );

	try {
		Document doc = getDocument( data );
		MongoCollection<Document> col = db.getCollection( collection );
		long start = System.currentTimeMillis();

		if ( doc.containsKey( "_id" ) ) {
			col.updateOne( new Document( "_id", doc.get( "_id" ) ), new Document("$set",doc) );
		} else {
			col.insertOne( doc );
		}

		_session.getDebugRecorder().execMongo( col, "save", doc, System.currentTimeMillis() - start );

		return cfBooleanData.TRUE;

	} catch ( Exception me ) {
		throwException( _session, me.getMessage() );
		return null;
	}
}
 
Example 11
Source Project: mongo-mapper   File: MongoMapperIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDoubleList() throws Exception {
    MongoCollection<TestEntityDoubleList> collection = db.getCollection("test_doublelist", TestEntityDoubleList.class);
    collection.drop();

    TestEntityDoubleList entity = new TestEntityDoubleList();
    entity.setDoubleList(Arrays.asList(0.0, 6.5));

    collection.insertOne(entity);

    TestEntityDoubleList returned = collection.find().first();
    Assert.assertEquals(entity.getDoubleList(), returned.getDoubleList());
}
 
Example 12
Source Project: mongo-mapper   File: MongoMapperIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericList() {
    MongoCollection<TestEntityList> collection = db.getCollection("test_list", TestEntityList.class);
    collection.drop();

    TestEntityEmbedded embeddedEntity1 = new TestEntityEmbedded();
    embeddedEntity1.setName("Entity 1");
    embeddedEntity1.setAge(1);

    TestEntityEmbedded embeddedEntity2 = new TestEntityEmbedded();
    embeddedEntity2.setName("Entity 2");
    embeddedEntity2.setAge(2);

    ArrayList<TestEntityEmbedded> list = new ArrayList<>();
    list.add(embeddedEntity1);
    list.add(embeddedEntity2);

    TestEntityList entity = new TestEntityList();
    entity.setList(list);

    collection.insertOne(entity);

    TestEntityList returned = collection.find().first();
    Assert.assertEquals(entity.getList().size(), returned.getList().size());
    Assert.assertEquals(entity.getList().get(0), returned.getList().get(0));
    Assert.assertEquals(entity.getList().get(1), returned.getList().get(1));
}
 
Example 13
Source Project: baleen   File: ReNounFact.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Save this fact to the given mongo collection
 *
 * @param collection to save to
 */
public void save(MongoCollection<Document> collection) {
  collection.insertOne(
      new Document()
          .append(SUBJECT_FIELD, subject)
          .append(ATTRIBUTE_FIELD, attribute)
          .append(OBJECT_FIELD, object)
          .append(SCORE_FIELD, score)
          .append(PATTERN_FIELD, pattern)
          .append(SENTENCE_FIELD, sentence));
}
 
Example 14
Source Project: SI   File: ResourceDAO.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void create(Resource res) throws OneM2MException {
	
	Document curDoc = getDocument(URI_KEY, res.getUri());
	if (curDoc != null) {
		// added to support logic to delete expired resource
		// logic added in 2016-12-27
		String expirationTime = curDoc.getString(EXPIRETIME_KEY);
		if(expirationTime != null && Utils.checkIfExpired(expirationTime)) {
			String resUri = curDoc.getString(URI_KEY);
			this.deleteDocument(URI_KEY, resUri);
		} else {
			throw new OneM2MException(RESPONSE_STATUS.CONFLICT,
					"Resource already exist!!! :" + res.getUri());
		}
	}		

	String strJson = resourceToJson(res);
	log.debug("Res json: {} ", strJson);
	
	String currentTime = getTimeString(LocalDateTime.now());
	res.setCreationTime(currentTime);
	res.setLastModifiedTime(currentTime);

	Document doc = Document.parse(strJson);
	doc.append(ResourceDAO.URI_KEY, res.getUri());
	doc.append(ResourceDAO.CRETIME_KEY, currentTime);
	doc.append(ResourceDAO.LASTMODTIME_KEY, currentTime);

	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);

	collection.insertOne(doc);
	
}
 
Example 15
Source Project: epcis   File: MongoCaptureUtil.java    License: Apache License 2.0 5 votes vote down vote up
public void captureJSONEvent(JSONObject event) {

		MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("EventData",
				BsonDocument.class);
		BsonDocument dbObject = BsonDocument.parse(event.toString());
		if (Configuration.isTriggerSupported == true) {
			TriggerEngine.examineAndFire("EventData", dbObject);
		}
		collection.insertOne(dbObject);
		Configuration.logger.info(" Event Saved ");
	}
 
Example 16
Source Project: grain   File: MongodbManager.java    License: MIT License 5 votes vote down vote up
/**
 * 插入一条记录
 * 
 * @param collectionName
 *            表名
 * @param mongoObj
 *            记录
 * @return
 */
public static boolean insertOne(String collectionName, MongoObj mongoObj) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		Document document = objectToDocument(mongoObj);
		collection.insertOne(document);
		return true;
	} catch (Exception e) {
		if (log != null) {
			log.error("插入document失败", e);
		}
		return false;
	}

}
 
Example 17
Source Project: skywalking   File: CaseController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/mongodb")
public String mongoDBCase() {
    try (MongoClient mongoClient = new MongoClient(host, port)) {
        MongoDatabase db = mongoClient.getDatabase("test-database");
        // CreateCollectionOperation
        db.createCollection("testCollection");

        MongoCollection<Document> collection = db.getCollection("testCollection");
        Document document = Document.parse("{id: 1, name: \"test\"}");
        // MixedBulkWriteOperation
        collection.insertOne(document);

        // FindOperation
        FindIterable<Document> findIterable = collection.find(eq("name", "org"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.updateOne(eq("name", "org"), BsonDocument.parse("{ $set : { \"name\": \"testA\"} }"));

        // FindOperation
        findIterable = collection.find(eq("name", "testA"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.deleteOne(eq("id", "1"));

        // DropDatabaseOperation
        mongoClient.dropDatabase("test-database");
    }
    return "success";
}
 
Example 18
Source Project: epcis   File: MongoCaptureUtil.java    License: Apache License 2.0 5 votes vote down vote up
public void captureJSONEvent(JSONObject event) {

		MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("EventData",BsonDocument.class);
		BsonDocument dbObject = BsonDocument.parse(event.toString());
		if (Configuration.isTriggerSupported == true) {
			TriggerEngine.examineAndFire("EventData", dbObject);
		}
		collection.insertOne(dbObject);
		Configuration.logger.info(" Event Saved ");
	}
 
Example 19
@Test
public void testStream_whenWatchAll() {
    IList<Document> list = jet.getList("list");

    String connectionString = mongoContainer.connectionString();
    long value = startAtOperationTime.getValue();

    StreamSource<? extends Document> source = MongoDBSourceBuilder
            .streamAll(SOURCE_NAME, () -> MongoClients.create(connectionString))
            .destroyFn(MongoClient::close)
            .searchFn(client -> {
                List<Bson> aggregates = new ArrayList<>();
                aggregates.add(Aggregates.match(new Document("fullDocument.val", new Document("$gt", 10))
                        .append("operationType", "insert")));

                aggregates.add(Aggregates.project(new Document("fullDocument.val", 1).append("_id", 1)));
                return client.watch(aggregates);
            })
            .mapFn(ChangeStreamDocument::getFullDocument)
            .startAtOperationTimeFn(client -> new BsonTimestamp(value))
            .build();

    Pipeline p = Pipeline.create();
    p.readFrom(source)
     .withNativeTimestamps(0)
     .writeTo(Sinks.list(list));

    Job job = jet.newJob(p);

    MongoCollection<Document> col1 = collection("db1", "col1");
    MongoCollection<Document> col2 = collection("db1", "col2");
    MongoCollection<Document> col3 = collection("db2", "col3");

    col1.insertOne(new Document("val", 1));
    col1.insertOne(new Document("val", 11).append("foo", "bar"));
    col2.insertOne(new Document("val", 2));
    col2.insertOne(new Document("val", 12).append("foo", "bar"));
    col3.insertOne(new Document("val", 3));
    col3.insertOne(new Document("val", 13).append("foo", "bar"));

    assertTrueEventually(() -> {
        assertEquals(3, list.size());
        list.forEach(document -> assertNull(document.get("foo")));

        assertEquals(11, list.get(0).get("val"));
        assertEquals(12, list.get(1).get("val"));
        assertEquals(13, list.get(2).get("val"));
    });

    col1.insertOne(new Document("val", 4));
    col1.insertOne(new Document("val", 14).append("foo", "bar"));
    col2.insertOne(new Document("val", 5));
    col2.insertOne(new Document("val", 15).append("foo", "bar"));
    col2.insertOne(new Document("val", 6));
    col2.insertOne(new Document("val", 16).append("foo", "bar"));

    assertTrueEventually(() -> {
        assertEquals(6, list.size());
        list.forEach(document -> assertNull(document.get("foo")));

        assertEquals(14, list.get(3).get("val"));
        assertEquals(15, list.get(4).get("val"));
        assertEquals(16, list.get(5).get("val"));
    });

    job.cancel();

}
 
Example 20
Source Project: javase   File: MongoDbClient.java    License: MIT License 4 votes vote down vote up
public static void main( String args[] ) {
	
      try{
		
         // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
			
         // Now connect to your databases
         MongoDatabase db = mongoClient.getDatabase("test"); 
         //DB db = mongoClient.getDB( "test" );
         System.out.println("Connect to database successfully");
         //boolean auth = db.authenticate(myUserName, myPassword);
         //System.out.println("Authentication: "+auth);
		
         //DBCollection coll = db.createCollection("mycol", null);
         if (db.getCollection("mycol") != null) {
        	 db.getCollection("mycol").drop();
         }
         db.createCollection("mycol");
         
         System.out.println("Collection created successfully");
         
         // /*DBCollection*/ coll = db.getCollection("mycol");
         MongoCollection<Document> coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
//         BasicDBObject doc = new BasicDBObject("title", "MongoDB").
//            append("description", "database").
//            append("likes", 100).
//            append("url", "http://www.tutorialspoint.com/mongodb/").
//            append("by", "tutorials point");
         Document doc = new Document("title", "MongoDB").
               append("description", "database").
               append("likes", 100).
               append("url", "http://www.tutorialspoint.com/mongodb/").
               append("by", "tutorials point"); 
				
         //coll.insert(doc);
         coll.insertOne(doc);
         System.out.println("Document inserted successfully: " + doc.toJson());
         
         
         /*DBCollection*/ coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
         //DBCursor cursor = coll.find();
         FindIterable<Document> iterableFind = coll.find();
         MongoCursor<Document> cursor = iterableFind.iterator();
         int i = 1;
			
         while (cursor.hasNext()) { 
            System.out.println("Inserted Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
         
         mongoClient.close();
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }