MongoDB Aggregation - 如何使用 spring-data-mongodb 将查询表达式应用到匹配阶段?

     2023-02-16     84

关键词:

【中文标题】MongoDB Aggregation - 如何使用 spring-data-mongodb 将查询表达式应用到匹配阶段?【英文标题】:MongoDB Aggregation - How can i apply query expression into match stage using spring-data-mongodb? 【发布时间】:2021-12-06 23:59:05 【问题描述】:

我有包含动态字段的文档,我需要为给定的复杂查询条件找到匹配记录的计数

示例实体

@Document(collection = "UserAttributes")
public class UserAttributesEntity 

    @Id
    @Getter
    private String id;

    @NotNull
    @Size(min = 1)
    @Getter @Setter
    private String userId;

    @NotNull
    @Getter @Setter
    private Map<String, Object> attributes = new HashMap<>();

示例数据


    "_id" : ObjectId("6164542362affb14f3f2fef6"),
    "userId" : "89ee6942-289a-48c9-b0bb-210ea7c06a88",
    "attributes" : 
        "age" : 61,
        "name" : "Name1"
    
,

    "_id" : ObjectId("6164548045cc4456792d5325"),
    "userId" : "538abb29-c09d-422e-97c1-df702dfb5930",
    "attributes" : 
        "age" : 40,
        "name" : "Name2",
        "location" : "IN"
    

预期的查询表达式

"((attributes.name == 'Name1' && attributes.age > 40) OR (attributes.location  == 'IN'))

$match 的 MongoDB 聚合查询如下所示,但通过 spring mongo db api 不可用:

 
    $expr: 
     
        "$and": [
            "$gt": ["$attributes.age", 40]
        , 
            "$eq": ["$attributes.name", "Name2"]
        ] 
    

我这里有什么遗漏吗?

库使用:org.springframework.data:spring-data-mongodb:3.1.1

【问题讨论】:

【参考方案1】:

您可以实现自己的AggregationOperation 来处理您不同的情况。 我自己的代码没试过,不过应该是这样的:

AggregationOperation myMatch (List<Document> conditions) 

    return new AggregationOperation() 

        @Override
        public String getOperator() 
            return "$match";
        

        @Override
        public Document toDocument(AggregationOperationContext context) 
            return new Document("$match",
                    new Document("$expr",
                            new Document("$and", conditions)
                    )
            );
        
    ;

并以这种方式调用它(以匹配您的问题查询):

void callMyMatch() 
    myMatch(List.of(
        new Document("$gt", List.of("$attributes.age", 40)),
        new Document("$eq", List.of("$attributes.name", "Name2"))
    ));

【讨论】:

谢谢@orid。是的,我可以执行上述方法,甚至我也可以尝试根据查询动态创建 Criteria 对象,但我会期待一些具有嵌套条件的复杂查询,因此希望我是否可以简单地使用 SPEL 来评估查询表达式?类似问题:***.com/questions/69635474/… 寻找一种直接传入表达式而不像上面那样构建它的方法:"((attributes.name == 'Name1' &amp;&amp; attributes.age &gt; 40) OR (attributes.location == 'IN'))"

mongoDB: Aggregation - 是不是有相当于原生 node.js 驱动程序的 $lookup 连接?

】mongoDB:Aggregation-是不是有相当于原生node.js驱动程序的$lookup连接?【英文标题】:mongoDB:Aggregation-Isthereaequivalentofthe$lookupjoinsforthenativenode.jsdriver?mongoDB:Aggregation-是否有相当于原生node.js驱动程序的$lookup连接?【发布时间】:2016-02... 查看详情

使用 C# Fluent Aggregation Framework 的 MongoDB 异常

】使用C#FluentAggregationFramework的MongoDB异常【英文标题】:MongoDBexceptionusingC#FluentAggregationFramework【发布时间】:2017-01-0819:36:33【问题描述】:我正在尝试使用C#驱动程序中的MongoDB流式聚合语法编写一个非常简单的分组查询。我正在... 查看详情

MongoDB Aggregation SQL Union 和 SQL Exists like 子句

】MongoDBAggregationSQLUnion和SQLExistslike子句【英文标题】:MongoDBAggregationSQLUnionandSQLExistslikeclause【发布时间】:2015-06-0221:32:01【问题描述】:我想对这样的数据进行MongoDB聚合查询:集合A_id:1,Active:true,hasQuery:false,Running:false,_id:2,Active:t... 查看详情

Spring Data MongoDB:如何用 Spring Aggregation 描述聚合 $merge?

】SpringDataMongoDB:如何用SpringAggregation描述聚合$merge?【英文标题】:SpringDataMongoDB:Howtodescribeaggregation$mergewithSpringAggregation?【发布时间】:2021-05-1518:50:18【问题描述】:我想通过MongoTemplate执行的代码:$merge:into:\'someCollection\',on:"_... 查看详情

MongoDB Aggregation - $unwind order 文档是不是与嵌套数组 order 相同

】MongoDBAggregation-$unwindorder文档是不是与嵌套数组order相同【英文标题】:MongoDBAggregation-Does$unwindorderdocumentsthesamewayasthenestedarrayorderMongoDBAggregation-$unwindorder文档是否与嵌套数组order相同【发布时间】:2020-11-1715:03:18【问题描述】:... 查看详情

MongoDB Aggregation - $unwind order 文档是不是与嵌套数组 order 相同

】MongoDBAggregation-$unwindorder文档是不是与嵌套数组order相同【英文标题】:MongoDBAggregation-Does$unwindorderdocumentsthesamewayasthenestedarrayorderMongoDBAggregation-$unwindorder文档是否与嵌套数组order相同【发布时间】:2020-11-1715:03:18【问题描述】:... 查看详情

如何使“LIKE”查询在 MongoDB 中工作?

】如何使“LIKE”查询在MongoDB中工作?【英文标题】:Howtomake"LIKE"queryworkinMongoDB?【发布时间】:2011-04-2700:44:33【问题描述】:我有一个街道名称列表,我想选择所有以“Al”开头的名称。在我的MySQL中,我会做类似的事情S... 查看详情

如何使`org.mongodb.driver.cluster`在spring boot中使用嵌入式mongodb?

】如何使`org.mongodb.driver.cluster`在springboot中使用嵌入式mongodb?【英文标题】:Howtomake`org.mongodb.driver.cluster`useembeddedmongodbwithinspringboot?【发布时间】:2020-07-0107:19:05【问题描述】:尝试将嵌入式mongodb用于我的springlocal配置文件。这... 查看详情

如何在pentaho mongodb输入查询(聚合)中传递变量

...传递变量【英文标题】:howpassvariableinpentahomongodbinputquery(aggregation)【发布时间】:2019-09-2022:09:19【问题描述】:我想通过聚合在MongoDB输入中使用变量替换。但这不起作用。前任:db.fch.aggregate([$match:\'date_field\':$gte:"$lastOneHour",.. 查看详情

如何使 junit 测试在 springboot 应用程序中使用嵌入式 mongoDB?

】如何使junit测试在springboot应用程序中使用嵌入式mongoDB?【英文标题】:HowtomakethejunittestsusetheembeddedmongoDBinaspringbootapplication?【发布时间】:2018-06-1021:36:32【问题描述】:我正在学习springboot并创建了一个简单的springboot应用程序... 查看详情

如何在 MongoDB 2.4.x 中存储附加数据以使其符合 geoJSON 格式

】如何在MongoDB2.4.x中存储附加数据以使其符合geoJSON格式【英文标题】:HowtostoreadditionaldatainMongoDB2.4.xsuchthatitconformstogeoJSONformatting【发布时间】:2016-11-2509:28:04【问题描述】:我有一个数据库集合,它遵循地理点位置的geoJSON格式... 查看详情

Java MongoDB 投影

...数组元素被过滤:https://docs.mongodb.com/manual/reference/operator/aggregation/filter/#exp._S_filterdb.sales.aggregate 查看详情

MongoDb:聚合 $lookup

】MongoDb:聚合$lookup【英文标题】:MongoDb:aggregation$lookup【发布时间】:2022-01-0515:59:14【问题描述】:鉴于以下集合。我必须得到标题字段并结合到标识符凭据:_id:..title:..USER_CREDENTIAL:_id:..credential_id:..(fromcredentialcollection)created_a... 查看详情

mongoDB中的子查询问题

...码,但没有成功:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/selectcount(* 查看详情

mongodb语句和sql语句对应(sqltoaggregationmappingchart)

SQLtoAggregationMappingCharthttps://docs.mongodb.com/manual/reference/sql-aggregation-comparison/OnthispageExamplesAdditionalResourcesThe aggregationpipeline allowsMongoDBtoprovidenativeaggr 查看详情

Spring - mongodb - 聚合 - 'cursor' 选项是必需的

...聚合-\\\'cursor\\\'选项是必需的【英文标题】:Spring-mongodb-aggregation-The\'cursor\'optionisrequiredSpring-mongodb-聚合-\'cursor\'选项是必需的【发布时间】:2018-07-0712:09:06【问题描述】:执行以下聚合管道:publicvoidgetMostLikedItems()UnwindOperatio 查看详情

删除 Mongo::Collection::View::Aggregation 中的所有文档

】删除Mongo::Collection::View::Aggregation中的所有文档【英文标题】:deletingalldocumentsinMongo::Collection::View::Aggregation【发布时间】:2015-08-1207:38:59【问题描述】:如何删除Mongo::Collection::View::Aggregation对象持有的所有文档?编辑1我需要删... 查看详情

MongoDB Mongoose 聚合/数学运算

】MongoDBMongoose聚合/数学运算【英文标题】:MongoDBMongooseaggregation/mathoperations【发布时间】:2017-09-1300:56:42【问题描述】:我无法理解$aggregation方法在Mongoose中的工作原理。老实说,我在mongoose文档中找不到任何代码示例(我什至... 查看详情