java - How can I check if particular value exists using Java driver 3.6+ mongodb?
问题描述
I have documents like:
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
}
解决方案
要检查特定值是否存在,您可以使用方法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
}
推荐阅读
- node.js - 文档中间件、模型中间件、聚合中间件、查询中间件有什么区别?
- ruby - 谁能解释一下 :hard_wrap 是如何工作的?
- javascript - 当实时位置到达标记位置时,如何调用显示“您已到达目的地”警报的函数?ReactJS 和传单
- javascript - 如何使用 React Native 创建底部标签导航
- javascript - 给定数组的 Observable,优化 Rxjs 中重复的昂贵计算
- javascript - 包含对象到平面对象数组的对象数组
- r - Firth 逻辑回归中的错误消息
- java - AspectJ @Around 和 @After 抛出相同的方法不起作用
- python - 为什么 funcion self.spacy_nlp(phrase) 不起作用
- angular - 单击按钮展开 Angular Material 行