title: How to avoid an exception Prematurely reached end of stream using mongoDB Java driver 3.4+ or 3.6+? (during insertion)
body: <p>I'm trying to insert some documents to capped collection using this snippet of code:</p>
  
  <pre><code>            // get document with specific fields
              Document found = collection.find().first();
              String getTitle = (String) found.get("title");
              String getUrl = (String) found.get("url");
              String getImg = (String) found.get("img");
              String getPrice = (String) found.get("price");
  
              // document which I want to get as new
              Document doc = collection.find(new Document("title", getTitle)
                      .append("url", getUrl)
                      .append("img", getImg)
                      .append("price", getPrice)
                      .append("sent", true)).first();
  
              // if the document doesn't exist, then insert as new
              if (doc == null) {
               collection.insertOne(new Document("title", getTitle)
                     .append("url", getUrl)
                     .append("img", getImg)
                     .append("price", getPrice)
                     .append("sent", true));
          }
  </code></pre>
  
  <p>It means - rewriting documents. I'm inserting new documents with one more field instead of older docs, because capped collection doesn't allow to update existing document with another size. <strong>Since I get an exception: Cannot change the size of a document in a capped collection</strong>.</p>
  
  <p>Older doc looks like:</p>
  
  <p><a href="https://i.stack.imgur.com/b3NCx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b3NCx.png" alt="enter image description here"></a></p>
  
  <p>New will be as:</p>
  
  <p><a href="https://i.stack.imgur.com/JKal6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JKal6.png" alt="enter image description here"></a></p>
  
  <p>And this code works fine, but after a while <strong>(during insertion)</strong> I'm getting constantly an error:</p>
  
  <pre><code>com.mongodb.MongoSocketReadException: Prematurely reached end of stream
      at com.mongodb.connection.SocketStream.read(SocketStream.java:88)
      at com.mongodb.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:491)
      at com.mongodb.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:221)
      at com.mongodb.connection.CommandHelper.receiveReply(CommandHelper.java:134)
      at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:121)
      at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
      at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83)
      at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43)
      at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
      at com.mongodb.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:46)
      at com.mongodb.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:381)
      at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:96)
      at com.mongodb.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:82)
      at com.mongodb.connection.DefaultServer.getConnection(DefaultServer.java:72)
      at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:86)
      at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:237)
      at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:212)
      at com.mongodb.operation.FindOperation.execute(FindOperation.java:482)
      at com.mongodb.operation.FindOperation.execute(FindOperation.java:79)
      at com.mongodb.Mongo.execute(Mongo.java:772)
      at com.mongodb.Mongo$2.execute(Mongo.java:759)
      at com.mongodb.FindIterableImpl$FindOperationIterable.first(FindIterableImpl.java:207)
      at com.mongodb.FindIterableImpl.first(FindIterableImpl.java:148)
      at project.Bot.onUpdateReceived(Bot.java:347)
  </code></pre>
  
  <p>As I correctly understand, the error appears on the line (maybe simply formatting problem):</p>
  
  <pre><code> Document found = collection.find().first();
  </code></pre>
  
  <p>I researched and tried to solve the error using this <a href="https://stackoverflow.com/a/39524128/8370915">code</a> like (I'm using free Tier M0 cluster):</p>
  
  <pre><code>  MongoCredential credential = MongoCredential.createCredential("admin1", "admin", "mypassword".toCharArray());
          MongoClientSettings settings = MongoClientSettings.builder()
                  .credential(credential)
                  .retryWrites(true)
                  .applyToConnectionPoolSettings(builder -&gt;
                          builder.maxConnectionIdleTime(60000, TimeUnit.MILLISECONDS))
                  .applyToSocketSettings(builder -&gt;
                          builder.keepAlive(true))
                  .applyToSslSettings(builder -&gt; builder.enabled(true))
                  .applyToClusterSettings(builder -&gt; {
                      builder.hosts(Arrays.asList(
                              new ServerAddress("cluster0-shard-00-00-ox90k.mongodb.net", 27017),
                              new ServerAddress("cluster0-shard-00-01-ox90k.mongodb.net", 27017),
                              new ServerAddress("cluster0-shard-00-02-ox90k.mongodb.net", 27017)
                      ));
                      builder.requiredReplicaSetName("Cluster0-shard-0");
                  })
                  .build();
  
          MongoClient mongoClient = MongoClients.create(settings);
  </code></pre>
  
  <p>The same error: <code>com.mongodb.MongoSocketReadException: Prematurely reached end of stream
  </code></p>
  
  <p><strong>Updated:</strong>
  Tried instead of rewriting full document, to change just one field like:</p>
  
  <pre><code>Document found = database.getCollection("capped_collection").find(new Document("title", title)
                  .append("url", url)
                  .append("img", img)
                  .append("price", price)).first();
  
          if (found == null) {
              collection.insertOne(new Document("title", title)
                              .append("url", url)
                              .append("img", img)
                              .append("price", price)
                              .append("sent", false));
  
      Document doc = collection.find(eq("sent", false)).first();
  
      if(doc != null){
       collection.updateOne(eq("sent", false), new Document("$set", new Document("sent", true)));
      }
  </code></pre>
  
  <p>But still have:</p>
  
  <pre><code>com.mongodb.MongoSocketReadException: Prematurely reached end of stream
  </code></pre>
  
  <hr>
  
  <p>Tried to change <a href="https://stackoverflow.com/a/43761945/8370915">version</a> , the result is <a href="https://dba.stackexchange.com/questions/219003/not-authorized-on-admin-to-execute-command-mongodb-atlas-m0-free-tier-cluster">here</a>.</p>
  
  <p>Does anyone know what I need to correct or how to solve the error <code>Prematurely reached end of stream</code>?</p>
  
  <p>I appreciate any help.</p>