You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Mongo Shell的$expr查询转换为Spring Boot的MongoTemplate实现?

用MongoTemplate实现数组完全匹配查询

集合数据结构

[
  {
    "_id": 1,
    "favorite": {
      "color": "red",
      "foods": {
        "fruits": "banana",
        "fastfood": [
          "burger",
          "sandwich"
        ]
      }
    }
  },
  {
    "_id": 2,
    "favorite": {
      "color": "green",
      "foods": {
        "noodles": "ramen",
        "fastfood": [
          "fries",
          "burger",
          "corn dog"
        ]
      }
    }
  },
  {
    "_id": 3,
    "favorite": {
      "color": "red",
      "foods": {
        "soup": "cream soup"
      }
    }
  }
]

需求

查询favorite.foods.fastfood数组与["burger", "sandwich"]完全一致的文档(元素顺序、数量、内容必须完全匹配)。

原始Mongo Shell查询

db.collection.find({
  $expr: {
    $eq: [
      ["burger", "sandwich"],
      "$favorite.foods.fastfood"
    ]
  }
})

MongoTemplate实现方案

在Spring Boot中,可通过Criteria结合Document构造$expr逻辑,直接映射Shell查询的逻辑,代码示例如下:

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.bson.Document;
import java.util.Arrays;

// 注入MongoTemplate实例
@Autowired
private MongoTemplate mongoTemplate;

public List<YourDocumentEntity> getMatchingFastfoodDocs() {
    // 定义要匹配的目标数组
    String[] targetFastfood = {"burger", "sandwich"};
    
    // 构建$expr查询条件
    Criteria criteria = Criteria.where("$expr").is(
        new Document("$eq", Arrays.asList(
            targetFastfood,
            "$favorite.foods.fastfood"
        ))
    );
    
    // 执行查询并返回结果
    Query query = new Query(criteria);
    return mongoTemplate.find(query, YourDocumentEntity.class);
}

如果需要用聚合查询实现,逻辑完全一致,代码如下:

import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.bson.Document;
import java.util.Arrays;

public List<YourDocumentEntity> getMatchingFastfoodWithAggregation() {
    String[] targetFastfood = {"burger", "sandwich"};
    
    MatchOperation match = MatchOperation.match(
        Criteria.where("$expr").is(
            new Document("$eq", Arrays.asList(targetFastfood, "$favorite.foods.fastfood"))
        )
    );
    
    Aggregation aggregation = Aggregation.newAggregation(match);
    AggregationResults<YourDocumentEntity> results = mongoTemplate.aggregate(
        aggregation, 
        "your_collection_name", 
        YourDocumentEntity.class
    );
    
    return results.getMappedResults();
}

注意事项

  • 请将YourDocumentEntity替换为你项目中对应集合的实体类,确保实体类的字段映射与集合结构一致(嵌套字段可通过嵌套类或@Field注解定义)。
  • 若不需要严格匹配元素顺序,可将上述代码中的$eq替换为$setEquals操作符,此时会忽略元素顺序,仅匹配元素集合是否一致。

内容的提问来源于stack exchange,提问作者Abhijit Mondal Abhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:15:18