本文整理匯總了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);
}
}
示例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();
}
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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));
}
示例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()));
}
示例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();
}
示例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);
}
示例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();
}
示例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));
}
示例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());
}