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


Java MongoCollection.insertMany方法代碼示例

本文整理匯總了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);
    }
}
 
開發者ID:jython234,項目名稱:nectar-server,代碼行數:26,代碼來源:FTSController.java

示例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));
    }
 
開發者ID:axelspringer,項目名稱:polymorphia,代碼行數:22,代碼來源:PolymorphicTest.java

示例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;
	}
}
 
開發者ID:dianbaer,項目名稱:grain,代碼行數:28,代碼來源:MongodbManager.java

示例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);
	}
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:38,代碼來源:InsertDocumentsImpl.java

示例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);
    }
}
 
開發者ID:jiumao-org,項目名稱:wechat-mall,代碼行數:13,代碼來源:MongoCRUD.java

示例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);
}
 
開發者ID:jiumao-org,項目名稱:wechat-mall,代碼行數:8,代碼來源:MongoCRUD.java

示例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);
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:12,代碼來源:SimpleMongodbAccessor.java

示例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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:17,代碼來源:MongodbDataAccess.java

示例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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:16,代碼來源:MongodbDataAccess.java

示例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());
    }


}
 
開發者ID:yu199195,項目名稱:happylifeplat-transaction,代碼行數:46,代碼來源:MongoDbConnectDatabase.java

示例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());
}
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:58,代碼來源:MongoDBDataStore.java

示例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


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