mongodb - 检查数组包含元素 mongodb

标签 mongodb spring-boot aggregation-framework

ArrayList<String> labels = (ArrayList) payload.get("labels");
Aggregation aggregation = newAggregation(
      match(Criteria.where("user_id").is(id).and("page_id").is(pageId).and("labels").in(labels)),
                sort(Sort.Direction.DESC, "meta_data.user_data.time"),
                group(Fields.fields().and("first_name", "$meta_data.user_data.first_name").and("last_name", "$meta_data.user_data.last_name").and("profile_pic", "$meta_data.user_data.profile_pic").and("user_id", "$user_id").and("labels", "$labels").and("access_times","$meta_data.access_times"))
      );

AggregationResults<UsersMongoResult> groupResults = mongoTemplate.aggregate(aggregation, "chatuser_log", UsersMongoResult.class);

在文档标签数组中是这样的labels: ["123", "456"]

当 ArrayList labels = ["123"] 结果匹配时 但当 ArrayList labels = ["123", "789"] 时,它也匹配该文档。

如何解决这个问题?

最佳答案

摘自 in-operator 的文档:

If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. , , etc.)

如果要匹配包含所有指定值的数组,则需要 all-operator

where("user_id").is(id).and("page_id").is(pageId).and("labels").all(labels))

关于mongodb - 检查数组包含元素 mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44671467/

相关文章:

mongodb - 如何解释从 MongoDB 返回的 LastErrorObject 属性?

java - Spring webflux 中处理条件响应的正确方法是什么

java - Spring Boot RedisTemplate 等同于 incr 方法

spring - gradle持续构建支持SpringBoot吗?

regex - 使用正则表达式从 MongoDB 中提取子字符串列表

node.js - Mongoose 的全文搜索不起作用

mongodb - 如何向所有文档添加字段,其中前 100 个文档的值为 1,后 100 个文档的值为 2,依此类推?

java - 将 Java Spring 代码从 AggregationOutput 更改为 DBCollection 聚合方法

mongodb - 在 MongoDB 中执行搜索/投影时如何重命名字段?

javascript - 使用聚合 $lookup 和 $mergeObjects