本文整理汇总了Java中com.mongodb.client.MongoCollection.insertMany方法的典型用法代码示例。如果您正苦于以下问题:Java MongoCollection.insertMany方法的具体用法?Java MongoCollection.insertMany怎么用?Java MongoCollection.insertMany使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.mongodb.client.MongoCollection
的用法示例。
在下文中一共展示了MongoCollection.insertMany方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: buildChecksumDir
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
private static void buildChecksumDir(File dir, boolean isPublic, MongoCollection<Document> index) throws IOException {
File[] contents = dir.listFiles();
if(contents == null) return;
List<Document> toInsert = new CopyOnWriteArrayList<>();
for(File file : contents) {
if(file.isDirectory()) {
// Recursion: build for all in that directory
buildChecksumDir(file, isPublic, index);
} else {
NectarServerApplication.getThreadPoolTaskExecutor().submit(() -> {
try {
buildChecksumFile(file, index, toInsert, isPublic);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
if(!toInsert.isEmpty()) {
index.insertMany(toInsert);
}
}
示例2: polymorphiaTest
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
/************ DOMAIN MODEL END ************/
@Test
public void polymorphiaTest() {
MongoDatabase database = mongoClient.getDatabase(DB_NAME);
MongoCollection<Shape> collection = database.getCollection("entities").withDocumentClass(Shape.class);
Shape[] shapes = {new Circle(), new Square(), new Square(), new Circle()};
collection.insertMany(Arrays.asList(shapes));
FindIterable<Shape> shapesFoundIterable = collection.find();
List<Shape> foundShapes = new ArrayList<>();
for (Shape shape : shapesFoundIterable) {
LOGGER.info("Found shape {} of type {} in database", shape, shape.getClass().getSimpleName());
foundShapes.add(shape);
}
MatcherAssert.assertThat(foundShapes, CoreMatchers.hasItems(shapes));
}
示例3: insertMany
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
/**
* 插入list
*
* @param collectionName
* 表名
* @param list
* list
* @return
*/
public static boolean insertMany(String collectionName, List<MongoObj> list) {
MongoCollection<Document> collection = getCollection(collectionName);
try {
ArrayList<Document> documentList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
MongoObj mongoObj = list.get(i);
Document document = objectToDocument(mongoObj);
documentList.add(document);
}
collection.insertMany(documentList);
return true;
} catch (Exception e) {
if (log != null) {
log.error("插入documentList失败", e);
}
return false;
}
}
示例4: insertMultipleDocuments
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
/**
* This method insert the more than one document at a time
*/
@Override
public void insertMultipleDocuments() {
MongoDatabase db = null;
MongoCollection collection = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
Document journal = new Document("item", "journal")
.append("qty", 25).append("tags", asList("blank", "red"));
Document journalSize = new Document("h", 14).append("w", 21)
.append("uom", "cm");
journal.put("size", journalSize);
Document mat = new Document("item", "mat").append("qty", 85)
.append("tags", singletonList("gray"));
Document matSize = new Document("h", 27.9).append("w", 35.5)
.append("uom", "cm");
mat.put("size", matSize);
Document mousePad = new Document("item", "mousePad").append("qty",
25).append("tags", asList("gel", "blue"));
Document mousePadSize = new Document("h", 19).append("w", 22.85)
.append("uom", "cm");
mousePad.put("size", mousePadSize);
collection.insertMany(asList(journal, mat, mousePad));
log.info("Multiple Document Insert Successfully...");
} catch (MongoException | ClassCastException e) {
log.error("Exception occurred while insert **Multiple Document** : " + e, e);
}
}
示例5: 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);
}
}
示例6: insertBatch
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
public static void insertBatch(MongoCollection<Document> col, List<String> jsons) {
List<Document> docs = new ArrayList<Document>(jsons.size());
for (String json : jsons) {
docs.add(Document.parse(json));
}
col.insertMany(docs);
}
示例7: clearAndPopulateDB
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
@Before
public void clearAndPopulateDB() throws IOException {
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> userDocuments = db.getCollection("users");
userDocuments.drop();
List<Document> testUsers = new ArrayList<>();
testUsers.add(Document.parse("{\n" +
" name: \"Chris\",\n" +
" age: 25,\n" +
" company: \"UMM\",\n" +
" email: \"[email protected]\"\n" +
" }"));
testUsers.add(Document.parse("{\n" +
" name: \"Pat\",\n" +
" age: 37,\n" +
" company: \"IBM\",\n" +
" email: \"[email protected]\"\n" +
" }"));
testUsers.add(Document.parse("{\n" +
" name: \"Jamie\",\n" +
" age: 37,\n" +
" company: \"Frogs, Inc.\",\n" +
" email: \"[email protected]\"\n" +
" }"));
ObjectId samsId = new ObjectId();
BasicDBObject sam = new BasicDBObject("_id", samsId);
sam = sam.append("name", "Sam")
.append("age", 45)
.append("company", "Frogs, Inc.")
.append("email", "[email protected]");
samsIdString = samsId.toHexString();
userDocuments.insertMany(testUsers);
userDocuments.insertOne(Document.parse(sam.toJson()));
// It might be important to construct this _after_ the DB is set up
// in case there are bits in the constructor that care about the state
// of the database.
userController = new UserController("test");
}
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-2-spraguesanborn,代码行数:41,代码来源:UserControllerSpec.java
示例8: batchInsert
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
/**
* 批量插入数据
*/
public void batchInsert(String collectionName, List<Map<String, Object>> list) {
MongoCollection collection = mongoDatabase.getCollection(collectionName);
List<Document> documents = new ArrayList<>();
for (Map<String, Object> map : list) {
documents.add(new Document(map));
}
collection.insertMany(documents);
}
示例9: insertMany
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
/**
* 批量插入
*
* @param collectionName
* @param dataList
* @return
*/
public boolean insertMany(String collectionName, List<Map<String, Object>> dataList) {
MongoCollection collection = sMongoDatabase.getCollection(collectionName);
List<Document> documentList = new ArrayList<>();
for (Map<String, Object> data : dataList) {
documentList.add(new Document(data));
}
collection.insertMany(documentList);
return true;
}
示例10: insertModelList
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
/**
* 批量插入
*
* @param collectionName
* @param dataList
* @return
*/
public <T> boolean insertModelList(String collectionName, List<T> dataList) {
MongoCollection collection = sMongoDatabase.getCollection(collectionName);
List<Document> documentList = dataList.stream()
.map(data -> Document.parse(JSON.toJSONString(data)))
.collect(Collectors.toList());
collection.insertMany(documentList);
return true;
}
示例11: main
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
public static void main(String[] args) {
try {
//连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址
//ServerAddress()两个参数分别为 服务器地址 和 端口
ServerAddress serverAddress = new ServerAddress("192.168.1.78", 27017);
List<ServerAddress> addrs = new ArrayList<>();
addrs.add(serverAddress);
//MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码
MongoCredential credential = MongoCredential.createScramSha1Credential("xiaoyu", "happylife", "123456".toCharArray());
List<MongoCredential> credentials = new ArrayList<>();
credentials.add(credential);
//通过连接认证获取MongoDB连接
MongoClient mongoClient = new MongoClient(addrs, credentials);
//连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("happylife");
System.out.println("Connect to database successfully");
//获取集合 参数为“集合名称”
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("collectionName");
System.out.println("Collection mycol selected successfully");
//插入文档
/**
* 1. 创建文档 org.bson.Document 参数为key-value的格式
* 2. 创建文档集合List<Document>
* 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document)
* */
Document document = new Document("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("by", "Fly");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
mongoCollection.insertMany(documents);
System.out.println("Document inserted successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
示例12: insert
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Override
protected boolean insert(DataStoreMsg msg) {
boolean isSuccess = false;
String collectionName = (String) msg.get(DataStoreProtocol.MONGO_COLLECTION_NAME);
MongoCollection<Document> collection = this.datasource.getSourceConnect().getCollection(collectionName);
// collection no exist
if (null == collection) {
if (log.isTraceEnable()) {
log.warn(this, "MongoDB[" + this.datasource.getDataStoreConnection().getDbName() + "] Collection["
+ collectionName + "] NO EXIST.");
}
return adaptor.handleInsertResult(isSuccess, msg, this.datasource.getDataStoreConnection());
}
// prepare documents
List<Map<String, Object>> documents = (List<Map<String, Object>>) adaptor.prepareInsertObj(msg,
this.datasource.getDataStoreConnection());
if (null != documents) {
// convert to Document Object
List<Document> docs = new ArrayList<Document>();
for (Map<String, Object> dMap : documents) {
Document doc = new Document();
for (String key : dMap.keySet()) {
doc.append(key, dMap.get(key));
}
docs.add(doc);
}
// insert documents
try {
collection.insertMany(docs);
isSuccess = true;
}
catch (MongoException e) {
log.err(this, "INSERT MongoDB[" + this.datasource.getDataStoreConnection().getDbName() + "] Collection["
+ collectionName + "] Documents FAIL.", e);
}
}
return adaptor.handleInsertResult(isSuccess, msg, this.datasource.getDataStoreConnection());
}
示例13: clearAndPopulateDB
import com.mongodb.client.MongoCollection; //导入方法依赖的package包/类
@Before
public void clearAndPopulateDB() throws IOException {
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection<Document> flowerDocuments = db.getCollection("flowers");
flowerDocuments.drop();
List<Document> testFlowers = new ArrayList<>();
testFlowers.add(Document.parse("{\n" +
" _id: \"id-1\",\n" +
" commonName: \"tulip\",\n" +
" cultivar: \"cltv-tulip\",\n" +
" source: \"src-a\",\n" +
" gardenLocation: \"loc-1\",\n" +
" year: 2016\n" +
" }"));
testFlowers.add(Document.parse("{\n" +
" _id: \"id-2\",\n" +
" commonName: \"lily\",\n" +
" cultivar: \"cltv-lily\",\n" +
" source: \"src-a\",\n" +
" gardenLocation: \"loc-1\",\n" +
" year: 2016\n" +
" }"));
testFlowers.add(Document.parse("{\n" +
" _id: \"id-3\",\n" +
" commonName: \"daisy\",\n" +
" cultivar: \"cltv-daisy\",\n" +
" source: \"src-b\",\n" +
" gardenLocation: \"loc-2\",\n" +
" year: 2016\n" +
" }"));
ObjectId roseId = new ObjectId();
BasicDBObject rose = new BasicDBObject("_id", roseId);
rose = rose.append("commonName", "rose")
.append("cultivar", "cltv-rose")
.append("source", "src-b")
.append("gardenLocation", "loc-2")
.append("year", 2016);
roseIdString = roseId.toHexString();
flowerDocuments.insertMany(testFlowers);
flowerDocuments.insertOne(Document.parse(rose.toJson()));
// It might be important to construct this _after_ the DB is set up
// in case there are bits in the constructor that care about the state
// of the database.
flowerController = new FlowerController("test");
}
开发者ID:UMM-CSci-3601-S17,项目名称:digital-display-garden-iteration-2-spraguesanborn,代码行数:48,代码来源:FlowerControllerSpec.java