我在我的应用程序中使用 MongoDB,需要在 MongoDB 集合中插入多个文档。 我使用的版本是 1.6
我在这里看到了一个例子
http://docs.mongodb.org/manual/core/create/
在
批量插入多个文档部分
作者在哪里传递一个数组来执行此操作。
当我尝试相同时,但为什么它不允许,请告诉我如何一次插入多个文档??
package com;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
public class App {
public static void main(String[] args) {
try {
MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("at");
DBCollection collection = db.getCollection("people");
/*
* BasicDBObject document = new BasicDBObject();
* document.put("name", "mkyong"); document.put("age", 30);
* document.put("createdDate", new Date()); table.insert(document);
*/
String[] myStringArray = new String[] { "a", "b", "c" };
collection.insert(myStringArray); // Compilation error at this line saying that "The method insert(DBObject...) in the type DBCollection is not applicable for the arguments (String[])"
} catch (Exception e) {
e.printStackTrace();
}
}
}
请告诉我有什么方法可以通过java一次插入多个文档。
最佳答案
DBCollection.insert
接受 DBObject
类型的参数, List<DBObject>
或 DBObject
的数组s 用于一次插入多个文档。您正在传递一个字符串数组。
您必须手动填充文档(DBObject
s),将它们插入到 List<DBObject>
或 DBObject
的数组s 和最终 insert
他们。
DBObject document1 = new BasicDBObject();
document1.put("name", "Kiran");
document1.put("age", 20);
DBObject document2 = new BasicDBObject();
document2.put("name", "John");
List<DBObject> documents = new ArrayList<>();
documents.add(document1);
documents.add(document2);
collection.insert(documents);
上述代码段与您在 MongoDB shell 中发出的命令基本相同:
db.people.insert( [ {name: "Kiran", age: 20}, {name: "John"} ]);
https://stackoverflow.com/questions/18128490/