Java Code Examples for com.mongodb.client.MongoCollection.insertMany()

The following are Jave code examples for showing how to use insertMany() of the com.mongodb.client.MongoCollection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: nectar-server   File: FTSController.java   View Source Code Vote up 6 votes
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);
    }
}
 
Example 2
Project: polymorphia   File: PolymorphicTest.java   View Source Code Vote up 6 votes
/************  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));
    }
 
Example 3
Project: grain   File: MongodbManager.java   View Source Code Vote up 6 votes
/**
 * 插入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;
	}
}
 
Example 4
Project: mongodb-crud   File: InsertDocumentsImpl.java   View Source Code Vote up 5 votes
/**
 * 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);
	}
}
 
Example 5
Project: wechat-mall   File: MongoCRUD.java   View Source Code Vote up 5 votes
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);
    }
}
 
Example 6
Project: wechat-mall   File: MongoCRUD.java   View Source Code Vote up 5 votes
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);
}
 
Example 7
Project: digital-display-garden-iteration-2-spraguesanborn   File: UserControllerSpec.java   View Source Code Vote up 5 votes
@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");
}
 
Example 8
Project: dooo   File: SimpleMongodbAccessor.java   View Source Code Vote up 5 votes
/**
 * 批量插入数据
 */
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);
}
 
Example 9
Project: dooo   File: MongodbDataAccess.java   View Source Code Vote up 5 votes
/**
 * 批量插入
 *
 * @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;
}
 
Example 10
Project: dooo   File: MongodbDataAccess.java   View Source Code Vote up 5 votes
/**
 * 批量插入
 *
 * @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;
}
 
Example 11
Project: happylifeplat-transaction   File: MongoDbConnectDatabase.java   View Source Code Vote up 4 votes
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());
    }


}
 
Example 12
Project: happylifeplat-tcc   File: MongoDbConnectDatabase.java   View Source Code Vote up 4 votes
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());
    }


}
 
Example 13
Project: uavstack   File: MongoDBDataStore.java   View Source Code Vote up 4 votes
@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());
}
 
Example 14
Project: digital-display-garden-iteration-2-spraguesanborn   File: FlowerControllerSpec.java   View Source Code Vote up 4 votes
@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");
}