繁体   English   中英

MongoTemplate 至少匹配我传递的值的查询数组

[英]MongoTemplate Query array that match at least the values I'm passing

如果我将文档定义为

[
  {
    "title": "title",
    "tags": [ "cool", "amazing", "funny" ]
  },
  {
    "title": "another title",
    "tags": [ "nice", "amazing", "funny" ]
  }
]

我希望能够使用 MongoTemplate 进行查询,以便传递像 ["cool","amazing"] 这样的值列表,并返回上面的第一个集合,而不是第二个集合。 对于我要实现的目标, $in条件似乎还不够。 我尝试了$all条件,并从 Mongo 控制台按我的需要工作,但在我的代码中有些东西不起作用,我的查询需要很长时间才能详细说明。 使用$in运算符,我的代码运行得很快。 我在我的存储库中的方法(出于其他原因,我必须进行如下聚合):

public Page<MyDocument> findByProperties(String title, List<ObjectId> tags, Pageable page) {
        final List<Criteria> criteria = new ArrayList<>();
        Aggregation aggregation = null;

        
        if (title != null && !title.isEmpty()) {
            criteria.add(Criteria.where("title").is(title));
        }
        
        if (tags != null && !tags.isEmpty()) {
            criteria.add(Criteria.where("MyBook.tags").all(tags));
        }

        if (!criteria.isEmpty()) {
            aggregation = Aggregation.newAggregation(
                    Aggregation.lookup("from_collection", "_id", "idParent", "MyBook"),
                    Aggregation.unwind("MyBook"),
                    Aggregation.match(new Criteria().andOperator(criteria.toArray(new Criteria[0]))),
                    Aggregation.skip(page.getOffset()),
                    Aggregation.limit(page.getPageSize()),
                    Aggregation.sort(page.getSort())
            );
        } else {
            aggregation = Aggregation.newAggregation(
                    Aggregation.lookup("from_collection", "_id", "idParent", "MyBook"),
                    Aggregation.unwind("MyBook"),
                    Aggregation.skip(page.getOffset()),
                    Aggregation.limit(page.getPageSize()),
                    Aggregation.sort(page.getSort())
            );
        }

        List<MyDocument>  results  = mongoTemplate.aggregate(aggregation, "my_document", MyDocument.class).getMappedResults();

        return PageableExecutionUtils.getPage(results, page,
                () -> (long)results.size());
    } 

看着这个答案,我尝试了

criteria.add(Criteria.where("MyBook.tags").in(tags).all(tags));

但是没有任何改变,查询需要永远,而不是预期的 output。 请问有什么想法吗? 谢谢!

要查找 tags 数组字段是否包含 youe 数组的所有成员,您可以使用波纹管,如果您需要它在聚合管道中使用第二个。

在您的查询中,您有更多阶段和更多代码,如果您想询问更多是否可以提供示例数据和 JSON 中的预期 output,以及您想做什么,以便人们可以提供帮助。

查询1

  • 使用$all运算符查找

测试代码在这里

db.collection.find({"tags": {"$all": ["cool","amazing"]}})

查询2

  • 具有集合差异的聚合解决方案

测试代码在这里

aggregate(
[{"$match": 
    {"$expr": 
      {"$eq": [{"$setDifference": [["cool", "amazing"], "$tags"]}, []]}}}])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM