【问题标题】:Not all documents are inserted in MongoDB when using the async-driver for Java使用 Java 的异步驱动程序时,并非所有文档都插入 MongoDB
【发布时间】:2016-05-29 11:49:42
【问题描述】:

我正在试验 mongodb-async 驱动程序 (http://mongodb.github.io/mongo-java-driver/3.0/driver-async/) 并注意到奇怪的行为。我在底层代码中重现了奇怪的行为:

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){
        }
    }
}

我希望这段代码将 100.000 个文档插入到名为“mongotest”的 mongo 数据库的集合“coll”中。 但是,当我在运行此代码后检查元素数量时,丢失了数千个文档。

在 mongodb-shell 中运行此语句时

db.getCollection("coll").count()

结果我得到 93062。这个数字因每次运行而异,但永远不会达到 100.000。任何人都可以解释为什么当我使用此代码时,为什么不是所有对象都正确存储为 MongoDB 中的文档?我们在 3 台不同的机器上对此进行了测试,每台机器都表现出相同的行为。

我觉得这是一个与驱动程序相关的问题,因为在此之后我使用 node.js 编写了一个类似的实验:

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;

与 java 代码相比,此代码的运行时间更长,但当代码完成时,集合中的文档数量符合预期。

谁能解释为什么java-example不是这种情况,并可能提供解决方案?

【问题讨论】:

    标签: java node.js mongodb asynchronous


    【解决方案1】:

    您何时运行db.getCollection("coll").count() 来检查插入结果?

    检查结果时,可能插入过程尚未完成。


    2016-02-19 15:00 编辑

    我做了同样的测试,得到了同样的结果。

    但是当我更改以下行时

     Document doc = new Document("name"+ i.toString(), "TESTING"); 
    

     Document doc = new Document("_id", "name"+ i.toString());
    

    它恰好插入了 100000 个文档。

    【讨论】:

    • 我在 3 分钟后检查了它,然后在 10 分钟、30 分钟后再次检查......这个数字没有改变,所以我认为它停止做有意义的工作是公平的。
    • 有趣的是,在第二个示例中它确实插入了 100000 个文档。你对这种奇怪的行为有什么解释吗?
    猜你喜欢
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多