首页 > 解决方案 > How can I check if particular value exists using Java driver 3.6+ mongodb?

问题描述

I have documents like:

enter image description here

My query is Document query = new Document("sent", new Document("$exists", true));
Now I can check only if field exists, but I want to check if exists value of this field.

For example: if my document has field and value sent:true, then I need to do something.

As I understand, it would similar to this:

Document query =  new Document(...);

if(query) {
//to do something
}

UPD: enter image description here

标签: javamongodb

解决方案


要检查特定值是否存在,您可以使用方法count()$eq运算符:

 long count = collection.count(new Document("sent", new Document("$eq", true)));

 if (count < 5) { // if the number of documents less than 5 has value as true
 // then to do something
 }

如果您只想检查现有字段,则需要使用$exists运算符:

long count = collection.count(new Document("sent", new Document("$exists", true)));

 if (count < 5) { // if the number of documents less than 5 has field named as sent
 // then to do something
 }

推荐阅读