插入 ArrayList mongodb [英] Insert ArrayList mongodb
问题描述
我正在尝试批量插入 100 个文档对象.我是否错误地使用了插入语句?
Im trying to batch insert 100 of the doc Objects. Am I using the insert statement incorrectly?
Mongo mongoClient = new Mongo( "localhost" , 27017 );
DB db = mongoClient.getDB( "user" );
DBCollection coll = db.getCollection("test");
BasicDBObject doc = new BasicDBObject("userName","James").append("random1", "feeof").append("random2", "ofeijfefe");
List<DBObject> postsList = new ArrayList<DBObject>();
for ( int i = 0; i != 100; i++)
{
postsList.add(doc);
}
coll.insert(postsList);
它不插入任何内容,当我检查最后一行时,它显示的值为 N/A.
It doesn't insert anything ,when i inspect the last line it shows the value as N/A.
推荐答案
我认为这就是这里发生的事情.
I think this is what is happening here.
对象 doc
被添加到 postsList
100 次.请记住,列表中的所有 100 个位置都是同一个对象.
The object doc
is being added to postsList
100 times. Remember it is the same object at all those 100 places in the list.
Mongo 为文档创建一个 _id
属性(如果它不存在).一旦它将此属性放在列表中的第一个 BasicDBObject
中,列表中的每个其他条目都会被修改为相同的 _id
.
Mongo creates an _id
attribute for a document if it isn't already there. Once it puts this attribute in the first BasicDBObject
in the list every other entry in the list gets modified with the same _id
.
我相信因为这个 _id
属性对于列表中的所有条目都是相同的(就像一个主键),所以只有第一个条目被插入.
I believe because this _id
attribute is same for all the entries in the list (which is like a primary key), only the first entry gets inserted.
您可以通过将 doc
的副本添加到列表中来解决此问题.试试这个:
You can solve this by adding a copy of the doc
to the list. Try this:
for (int i = 0; i < 100; i++) {
postsList.add((BasicDBObject) doc.copy());
}
这篇关于插入 ArrayList mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!