如何通过Java在MongoDB中一次插入多个文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18128490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert multiple documents at once in MongoDB through Java
提问by
I am using MongoDB in my application and was needed to insert multiple documents inside a MongoDB collection . The version I am using is of 1.6
我在我的应用程序中使用 MongoDB,需要在 MongoDB 集合中插入多个文档。我使用的版本是 1.6
I saw an example here
我在这里看到了一个例子
http://docs.mongodb.org/manual/core/create/
http://docs.mongodb.org/manual/core/create/
in the
在里面
Bulk Insert Multiple DocumentsSection
批量插入多个文档部分
Where the author was passing an array to do this .
作者正在传递一个数组来做到这一点。
When I tried the same , but why it isn't allowing , and please tell me how can I insert multiple documents at once ??
当我尝试相同时,但为什么不允许,请告诉我如何一次插入多个文档?
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();
}
}
}
Please let me know what is the way so that I can insert multiple documents at once through java .
请让我知道有什么方法可以通过 java 一次插入多个文档。
采纳答案by c.P.u1
DBCollection.insert
accepts a parameter of type DBObject
, List<DBObject>
or an array of DBObject
s for inserting multiple documents at once. You are passing in a string array.
DBCollection.insert
接受一个 type 参数DBObject
,List<DBObject>
或者一个DBObject
s数组,用于一次插入多个文档。您正在传递一个字符串数组。
You must manually populate documents(DBObject
s), insert them to a List<DBObject>
or an array of DBObject
s and eventually insert
them.
您必须手动填充文档DBObject
,将它们插入到一个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);
The above snippet is essentially the same as the command you would issue in the MongoDB shell:
上面的代码片段与您将在 MongoDB shell 中发出的命令基本相同:
db.people.insert( [ {name: "Kiran", age: 20}, {name: "John"} ]);
回答by Scott
As of MongoDB 2.6 and 2.12 version of the driver you can also now do a bulk insert operation. In Java you could use the BulkWriteOperation. An example use of this could be:
从 MongoDB 2.6 和 2.12 版本的驱动程序开始,您现在还可以执行批量插入操作。在 Java 中,您可以使用BulkWriteOperation。使用此方法的示例可能是:
DBCollection coll = db.getCollection("user");
BulkWriteOperation bulk = coll.initializeUnorderedBulkOperation();
bulk.find(new BasicDBObject("z", 1)).upsert().update(new BasicDBObject("$inc", new BasicDBObject("y", -1)));
bulk.find(new BasicDBObject("z", 1)).upsert().update(new BasicDBObject("$inc", new BasicDBObject("y", -1)));
bulk.execute();
回答by Vins
Before 3.0, you can use below code in Java
在 3.0 之前,您可以在 Java 中使用以下代码
DB db = mongoClient.getDB("yourDB");
DBCollection coll = db.getCollection("yourCollection");
BulkWriteOperation builder = coll.initializeUnorderedBulkOperation();
for(DBObject doc :yourList)
{
builder.insert(doc);
}
BulkWriteResult result = builder.execute();
return result.isAcknowledged();
If you are using mongodb version 3.0, you can use
如果您使用的是mongodb 3.0 版,则可以使用
MongoDatabase database = mongoClient.getDatabase("yourDB");
MongoCollection<Document> collection = database.getCollection("yourCollection");
collection.insertMany(yourDocumentList);
回答by Hemang Rami
Your insert record format like in MongoDB that query retire from any source EG.
您的插入记录格式就像 MongoDB 中的查询从任何源 EG 退休。
{
"_id" : 1,
"name" : a
}
{
"_id" : 2,
"name" : b,
}
it is mongodb 3.0
这是mongodb 3.0
FindIterable<Document> resulutlist = collection.find(query);
List docList = new ArrayList();
for (Document document : resulutlist) {
docList.add(document);
}
if(!docList.isEmpty()){
collectionCube.insertMany(docList);
}
回答by xameeramir
Creating Documents
创建文档
There're two principal commands for creating documents in MongoDB:
在 MongoDB 中创建文档有两个主要命令:
insertOne()
insertMany()
insertOne()
insertMany()
There're other ways as well such as Update
commands. We call these operations, upserts. Upserts occurs when there're no documents that match the selectorused to identify documents.
还有其他方法,例如Update
命令。我们称这些操作为 upsert。当没有与用于识别文档的选择器匹配的文档时,就会发生 Upsert 。
Although MongoDB inserts ID by it's own, We can manually insert custom IDs as well by specifying _id
parameter in the insert...()
functions.
虽然 MongoDB 是自己插入 ID,但我们也可以通过_id
在insert...()
函数中指定参数来手动插入自定义 ID 。
To insert multiple documents we can use insertMany()
- which takes an array of documents as parameter. When executed, it returns multiple id
s for each document in the array. To drop the collection, use drop()
command. Sometimes, when doing bulk inserts - we may insert duplicate values. Specifically, if we try to insert duplicate _id
s, we'll get the duplicate key error
:
要插入多个文档,我们可以使用insertMany()
- 它以文档数组作为参数。执行时,它id
为数组中的每个文档返回多个s。要删除集合,请使用drop()
命令。有时,在进行批量插入时 - 我们可能会插入重复的值。具体来说,如果我们尝试插入重复的_id
s,我们将得到duplicate key error
:
db.startup.insertMany( [ {_id:"id1", name:"Uber"}, {_id:"id2", name:"Airbnb"}, {_id:"id1", name:"Uber"}, ] );
MongoDB stops inserting operation, if it encounters an error, to supress that - we can supply ordered:false
parameter. Ex:
MongoDB 停止插入操作,如果遇到错误,以抑制它 - 我们可以提供ordered:false
参数。前任:
db.startup.insertMany( [ {_id:"id1", name:"Uber"}, {_id:"id2", name:"Airbnb"}, {_id:"id1", name:"Airbnb"}, ], {ordered: false} );