MongoDB Java 驱动程序更新了不匹配的子文档

MongoDB Java Driver updates unmatched sub-document

我正在使用 mongo-java-driver:3.3.0 并尝试使用 $inc 运算符和 findOneAndUpdate 更新我的子文档的一个值,但仅在特定条件下(id 比较和 greaterThan 过滤器)。

以下是重现问题的片段:

    MongoCollection<Document> coll = db.getCollection("update_increase");

    Document docBefore = new Document()
       .append("subdocs", Arrays.asList(
           new Document("id", "AAA").append("count", 10),
           new Document("id", "BBB").append("count", 20)
    ));
    coll.insertOne(docBefore);

    Document filter = new Document()
        .append("subdocs.id", "BBB")
        .append("subdocs.count", new Document("$gt", 7));

    Document update = new Document()
        .append("$inc", new Document("subdocs.$.count", -7));

    Document docAfter = coll.findOneAndUpdate(
        filter,
        update,
        new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER));

文档之前:

{ "_id" : { "$oid" : "5819c85977a8cb12f8d706c9" },
  "subdocs" : [
      { "id" : "AAA", "count" : 10 },
      { "id" : "BBB", "count" : 20 }
  ] 
}

docAfter:

{ "_id" : { "$oid" : "5819c85977a8cb12f8d706c9" },
  "subdocs" : [
      { "id" : "AAA", "count" : 3 },
      { "id" : "BBB", "count" : 20 }
  ]
}

我期望的是第二个子文档 (id:"BBB") 上的 count:13,但我得到了第一个子文档 (count:3) 的更新。

如果我删除 greaterThan 条件行 (.. new Document("$gt", 5) ..):

{ "_id" : { "$oid" : "5819c92577a8cb13404cfc91" },
  "subdocs" : [
      { "id" : "AAA", "count" : 10 },
      { "id" : "BBB", "count" : 13 }
  ]
}

我做错了什么?

谢谢!

这是 $elemMatch 的 java 等价物。

Document filter = new Document("subdocs", new Document().append("$elemMatch", new Document().append("id", "BBB").append("count", new Document("$gt", 7))));