When using async driver for Java, not all documents are inserted into mongodb
I'm trying to use the mongodb async driver( http://mongodb.github.io/mongo-java-driver/3.0/driver-async/ )And notice strange behavior I reproduced strange behavior in the underlying code:
import com.mongodb.async.SingleResultCallback; import com.mongodb.async.client.MongoClient; import com.mongodb.async.client.MongoClients; import com.mongodb.async.client.MongoCollection; import com.mongodb.async.client.MongoDatabase; import org.bson.Document; public class main { public static void main(String [] args) { MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("mongotest"); MongoCollection<Document> collection = database.getCollection("coll"); for(Integer i = 0; i < 100000; i++) { Document doc = new Document("name"+ i.toString(),"TESTING"); collection.insertOne(doc,new SingleResultCallback<Void>() { public void onResult(final Void result,final Throwable t) { System.out.println("Inserted!"); } }); } while(true){ } } }
I hope this code can insert 100000 documents into the collection 'coll' of Mongo database named "mongotest" However, when I check the number of elements after running this code, I lose thousands of documents
When running this statement in the mongodb shell
db.getCollection("coll").count()
As a result, I got 93062 This number varies from run to run, but it will never reach 100.000 Anyone can explain why when I use this code, all objects are not correctly stored in mongodb as documents? We tested on three different machines, and each machine exposed the same behavior
I think this is a driver related problem, because I use node JS wrote a similar experiment:
var express = require('express'); var MongoClient = require('mongodb').MongoClient; var app = express(); var url = 'mongodb://localhost:27017/mongotest'; MongoClient.connect(url,function (err,db) { for (var i = 0; i < 100000; i++) { var name = "name" + i; db.collection("coll").insertOne({ name: name },function(err,results) { if(err==null) { console.log("Sweet"); } }); } }); module.exports = app;
This code runs longer than Java code, but when the code is complete, the 100.000 document is expected to be in the collection
Can anyone explain why this is not the case with the java example and possibly provide a solution?
Solution
When do you run dB getCollection(“coll”). Count() to check the insertion result?
When checking the results, the insertion process may not be complete
2016-02-19 15:00 edit
I did the same test and the results were the same
But when I change the following lines
Document doc = new Document("name"+ i.toString(),"TESTING");
to
Document doc = new Document("_id","name"+ i.toString());
It just inserts 100000 decorations