如何使用Java驱动程序3.6+ mongodb检查特定值是否存在?

问题描述 投票:0回答:1

我有这样的文件:

enter image description here

我的queryDocument query = new Document("sent", new Document("$exists", true)); 现在我只能检查字段是否存在,但我想检查该字段是否存在。

例如:如果我的文档有字段和值sent:true,那么我需要做一些事情。

据我了解,它类似于:

Document query =  new Document(...);

if(query) {
//to do something
}

UPD:enter image description here

java mongodb
1个回答
0
投票

要检查是否存在特定值,可以将方法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
 }
© www.soinside.com 2019 - 2024. All rights reserved.