Java Code Examples for com.mongodb.client.MongoCollection#insertOne()
The following examples show how to use
com.mongodb.client.MongoCollection#insertOne() .
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: MongoAdapterTest.java From calcite with Apache License 2.0 | 7 votes |
@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 2
Source File: MongoSession.java From presto with Apache License 2.0 | 6 votes |
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 3
Source File: ResourceDAO.java From SI with BSD 2-Clause "Simplified" License | 6 votes |
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 4
Source File: MongoTest.java From game-server with MIT License | 6 votes |
@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 5
Source File: NamedQueryRegistration.java From epcis with Apache License 2.0 | 6 votes |
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 6
Source File: StatsDao.java From XBDD with Apache License 2.0 | 6 votes |
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 7
Source File: MongoMapperIT.java From mongo-mapper with Apache License 2.0 | 6 votes |
@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 File: MongoMapperIT.java From mongo-mapper with Apache License 2.0 | 6 votes |
@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 9
Source File: MongoMapperIT.java From mongo-mapper with Apache License 2.0 | 6 votes |
@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 10
Source File: MongoCaptureUtil.java From epcis with Apache License 2.0 | 5 votes |
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 11
Source File: MongoCaptureUtil.java From epcis with Apache License 2.0 | 5 votes |
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 12
Source File: CaseController.java From skywalking with Apache License 2.0 | 5 votes |
@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 13
Source File: MongodbManager.java From grain with MIT License | 5 votes |
/** * 插入一条记录 * * @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 14
Source File: MongoCollectionSave.java From openbd-core with GNU General Public License v3.0 | 5 votes |
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 15
Source File: ResourceDAO.java From SI with BSD 2-Clause "Simplified" License | 5 votes |
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 16
Source File: ReNounFact.java From baleen with Apache License 2.0 | 5 votes |
/** * 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 17
Source File: MongoMapperIT.java From mongo-mapper with Apache License 2.0 | 5 votes |
@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 18
Source File: MongoMapperIT.java From mongo-mapper with Apache License 2.0 | 5 votes |
@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 19
Source File: MongoDbClient.java From javase with MIT License | 4 votes |
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() ); } }
Example 20
Source File: MongoDBSourceTest.java From hazelcast-jet-contrib with Apache License 2.0 | votes |
@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(); }