我正在使用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));


docBefore:

{ "_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 }
  ]
}


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

如果我删除了大于条件线(.. 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))));

09-30 18:06