當前位置: 首頁>>代碼示例>>Java>>正文


Java MongoCollection.insertOne方法代碼示例

本文整理匯總了Java中com.mongodb.client.MongoCollection.insertOne方法的典型用法代碼示例。如果您正苦於以下問題:Java MongoCollection.insertOne方法的具體用法?Java MongoCollection.insertOne怎麽用?Java MongoCollection.insertOne使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.mongodb.client.MongoCollection的用法示例。


在下文中一共展示了MongoCollection.insertOne方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: insertUsingDocument

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * This method insert the document using Document object
 */
@Override
public void insertUsingDocument() {
	MongoDatabase db = null;
	MongoCollection collection = null;
	try {
		db = client.getDatabase(mongo.getDataBase());
		collection = db.getCollection(mongo.getSampleCollection());
		Document obj1 = new Document();
		obj1.put("name", "Sivaraman");
		obj1.put("age", 23);
		obj1.put("gender", "male");
		collection.insertOne(obj1);
		log.info("Document Insert Successfully using Document Obj...");
	} catch (MongoException | ClassCastException e) {
		log.error("Exception occurred while insert Value using **Document** : " + e, e);
	}
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:21,代碼來源:InsertDocumentsImpl.java

示例2: testInsert

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@Test
@Ignore
public void testInsert() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    try {
        MongoDatabase db = mongoClient.getDatabase("prova");
        MongoCollection<Document> coll = db.getCollection("prova");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("signature", "void test()");
        map.put("param", convert(new Object[0]));
        map.put("returnValue", 1);
        map.put("exception", convert(new IllegalAccessError("prova")));
        Document doc = new Document(map);
        coll.insertOne(doc);
        LOG.info(doc);
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        mongoClient.close();
    }
}
 
開發者ID:sap-nocops,項目名稱:Jerkoff,代碼行數:22,代碼來源:MongoTest.java

示例3: insertUsingMap

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * This method insert the document using Map
 */
@Override
public void insertUsingMap() {
	MongoDatabase db = null;
	MongoCollection collection = null;
	try {
		db = client.getDatabase(mongo.getDataBase());
		collection = db.getCollection(mongo.getSampleCollection());
		final Map<String, Object> empMap = new HashMap<>();
		empMap.put("_id", new Random().nextInt(999));
		empMap.put("name", "Vel");
		empMap.put("age", 25);
		empMap.put("desicnation", "Java Developer");
		empMap.put("gender", "Male");
		empMap.put("salary", "10000");
		log.info("Employ Details : " + empMap);
		collection.insertOne(new Document(empMap));
		log.info("Document Insert Successfully using Map...");
	} catch (MongoException | ClassCastException e) {
		log.error("Exception occurred while insert Value using **UsingMap** : " + e, e);
	}
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:25,代碼來源:InsertDocumentsImpl.java

示例4: executeInsert

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * @param dbName         表名
 * @param collectionName 集合名
 * @param saveJson       待存入JSON
 * @return 插入狀態或異常信息
 */
@SuppressWarnings("unchecked")
public JSONObject executeInsert(String dbName, String collectionName, JSONObject saveJson) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        Document doc = Document.parse(saveJson.toString());
        coll.insertOne(doc);
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
 
開發者ID:breakEval13,項目名稱:rocketmq-flink-plugin,代碼行數:25,代碼來源:MongoManager.java

示例5: insert

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@Override
public void insert(String collection, Map<String, Object> map) {
	try {
		LOG.info("Inserting document");
		MongoDatabase db = mongoClient.getDatabase(databaseName);
		MongoCollection<Document> coll = db.getCollection(collection);
		Document doc = new Document(map);
		LOG.debug(doc);
		coll.insertOne(doc);
		LOG.info("Document inserted");
	} catch (Exception e) {
		LOG.error(e);
	}
}
 
開發者ID:sap-nocops,項目名稱:Jerkoff,代碼行數:15,代碼來源:MongoDBDaoImpl.java

示例6: registerClientToDatabase

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
protected static JSONObject registerClientToDatabase(String ip) {
    MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");

    String uuid = UUID.randomUUID().toString();
    String authString = Util.generateNextRandomString();

    while(true) {
        if(clients.find(Filters.eq("uuid", uuid)).first() != null
                || clients.find(Filters.eq("auth", Util.computeSHA512(authString))).first() != null) {
            // We have a collision of UUID or auth string, although it should be VERY VERY rare
            uuid = UUID.randomUUID().toString();
            authString = Util.generateNextRandomString();
        } else {
            // UUID and Auth string are unique, break out
            break;
        }
    }

    Document clientDoc = new Document()
            .append("uuid", uuid)
            .append("auth", Util.computeSHA512(authString))
            .append("registeredAt", System.currentTimeMillis())
            .append("registeredBy", ip);
    clients.insertOne(clientDoc);

    NectarServerApplication.getEventLog().logEntry(EventLog.EntryLevel.INFO, "Client registration success from " + ip + ", new client was registered: " + uuid);

    JSONObject root = new JSONObject();
    root.put("uuid", uuid);
    root.put("auth", authString);
    return root;
}
 
開發者ID:jython234,項目名稱:nectar-server,代碼行數:34,代碼來源:AuthController.java

示例7: insert

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
public static void insert(MongoCollection<Document> col, String... jsons) {
    if (jsons.length == 1) {
        col.insertOne(Document.parse(jsons[0]));
    }
    else {
        List<Document> docs = new ArrayList<Document>(jsons.length);
        for (String json : jsons) {
            docs.add(Document.parse(json));
        }
        col.insertMany(docs);
    }
}
 
開發者ID:jiumao-org,項目名稱:wechat-mall,代碼行數:13,代碼來源:MongoCRUD.java

示例8: testStrangeId

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@Test
public void testStrangeId() {
    final MongoCollection<EntityWithStrangeId> collection = mongoClient.getDatabase(DB_NAME).getCollection("documents").withDocumentClass(EntityWithStrangeId.class);
    EntityWithStrangeId entityWithStrangeId = new EntityWithStrangeId();
    collection.insertOne(entityWithStrangeId);
    assertThat(entityWithStrangeId.id, is(not(nullValue())));
    EntityWithStrangeId foundEntityWithStrangeId = collection.find(Filters.eq("_id", entityWithStrangeId.id)).first();
    assertThat(foundEntityWithStrangeId, is(not(nullValue())));
    assertThat(foundEntityWithStrangeId.id, equalTo(entityWithStrangeId.id));
}
 
開發者ID:axelspringer,項目名稱:polymorphia,代碼行數:11,代碼來源:IdTest.java

示例9: insertOne

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
private void insertOne(AuditLogEntity input) {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {
    ObjectMapper objectMapper = MongoConfigObjectMapper.getInstance();
    objectMapper.writer().writeValue(baos, input);
  } catch (Exception e) {
    LOGGER.error("Exception at converting obj: {} to bson, cause: {}", input, e);
    throw ThrowableUtil.propagate(e);
  }
  MongoCollection<RawBsonDocument> collection =
      connector.getDatabase().getCollection(collectionName, RawBsonDocument.class);
  collection.insertOne(new RawBsonDocument(baos.toByteArray()));
}
 
開發者ID:scalecube,項目名稱:config,代碼行數:14,代碼來源:MongoConfigEventListener.java

示例10: clearAndPopulateDBAgain

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
public static void clearAndPopulateDBAgain(MongoDatabase testDB) throws IOException {
    testDB.drop();
    MongoCollection plants = testDB.getCollection("plants");
    MongoCollection beds = testDB.getCollection("beds");
    MongoCollection config = testDB.getCollection("config");
    config.insertOne(new Document().append("liveUploadId", "first uploadId"));

    addFirstUploadId(plants,beds,config);
    addSecondUploadId(plants,beds,config);
    addThirdUploadId(plants,beds,config);
    addGoogleChartsUploadId(plants,beds,config);

}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-revolverenguardia-1,代碼行數:14,代碼來源:PopulateMockDatabase.java

示例11: testMongo1

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@POST
@Path("testMongo1")
public void testMongo1(String jsonString) {

    MongoClient client = new MongoClient();
    client.listDatabaseNames().first();
    MongoDatabase db = client.getDatabase("apphubDataStore");
    db.listCollectionNames().first();
    MongoCollection<Document> collection = db.getCollection("test");
    collection.listIndexes().first();
    Document doc = new Document("name", "Amarcord Pizzeria")
            .append("contact",
                    new Document("phone", "264-555-0193").append("email", "[email protected]")
                            .append("location", Arrays.asList(-73.88502, 40.749556)))
            .append("stars", 2).append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));
    collection.insertOne(doc);
    collection.find().first();

    MongoClient client2 = new MongoClient("localhost:27017");
    db = client2.getDatabase("apphubDataStore");
    db.listCollectionNames().first();
    collection = db.getCollection("test");
    collection.listIndexes().first();

    client.close();
    client2.close();
}
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:28,代碼來源:TestRestService.java

示例12: insert

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
 * Insert a new document in to a collection.
 * 
 * @param collectionName name of the collection to insert the document in to.
 * @param dbObject the {@link Document} object to be inserted.
 */
public void insert(final String collectionName, final Document dbObject) {
    // Sanity checks
    if (StringUtils.isEmpty(collectionName)) {
        throw new IllegalArgumentException("insert :: Collection name should not be blank");
    }

    // Collection
    MongoCollection<Document> collection = this.database.getCollection(collectionName);
    collection.insertOne(dbObject);
}
 
開發者ID:millij,項目名稱:osm-processor,代碼行數:17,代碼來源:MongoStore.java

示例13: testExternalId

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@Test
public void testExternalId() {
    Pojo pojo = Pojo.builder().id(null).someOtherProperty("some nice string").build();
    MongoCollection<Pojo> collection = mongoClient.getDatabase("test").getCollection("documents").withDocumentClass(Pojo.class);
    collection.insertOne(pojo);

    Pojo readPojo = collection.find(Filters.eq("_id", pojo.getId())).first();

}
 
開發者ID:axelspringer,項目名稱:polymorphia,代碼行數:10,代碼來源:ExternalIdCodecProviderTest.java

示例14: test

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@Test
public void test() {
    MongoCollection<RichTextData> mongoCollection = mongoClient.getDatabase("test")
            .getCollection("documents")
            .withDocumentClass(RichTextData.class);

    RichTextData richText = new RichTextData();
    RichTextData.EntityMapEntry<Date> entityMapEntry = new RichTextData.EntityMapEntry<>();
    entityMapEntry.put("date", new Date());
    RichTextData.EntityMapEntry<Date> entityMapEntry1 = new RichTextData.EntityMapEntry<>();
    entityMapEntry1.put("date", new Date());
    entityMapEntry1.put("someDocumentProperty", new Document("propA", "String"));
    Map<String, RichTextData.EntityMapEntry<Date>> entityMap = new LinkedHashMap<>();
    entityMap.put("0", entityMapEntry);
    entityMap.put("1", entityMapEntry1);
    richText.put("entityMap", entityMap);
    richText.put("someOtherProperty", 11);
    richText.put("document", new Document("p1", new Date()));

    mongoCollection.insertOne(richText);


    RichTextData richTextRead = mongoCollection.find().first();
    assertNotNull(richTextRead);
    assertThat(richTextRead.getEntityMap(), IsInstanceOf.instanceOf(Map.class));
    assertThat(richTextRead.getEntityMap().get("0"), IsInstanceOf.instanceOf(RichTextData.EntityMapEntry.class));


}
 
開發者ID:axelspringer,項目名稱:polymorphia,代碼行數:30,代碼來源:SpecialFieldsMapCodecTest.java

示例15: testFieldNameLikeDiscriminatorKey

import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@Test(expected = IllegalArgumentException.class)
public void testFieldNameLikeDiscriminatorKey() {
    PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().
            register(Shape.class).
            register(ClassWithReservedFieldName.class).
            build();

    assertNotNull(pojoCodecProvider);
    CodecRegistry pojoCodecRegistry = fromRegistries(fromProviders(pojoCodecProvider), MongoClient.getDefaultCodecRegistry());
    MongoCollection<Shape> documents = mongoClient.getDatabase(DB_NAME)
            .getCollection("documents")
            .withCodecRegistry(pojoCodecRegistry)
            .withDocumentClass(Shape.class);
    documents.insertOne(new ClassWithReservedFieldName());
}
 
開發者ID:axelspringer,項目名稱:polymorphia,代碼行數:16,代碼來源:PolymorphicReflectionCodecTest.java


注:本文中的com.mongodb.client.MongoCollection.insertOne方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。