gpt4 book ai didi

java - Mongodb java驱动程序查询转换

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:54 25 4
gpt4 key购买 nike

我有以下数据结构

[{
"id": "1c7bbebd-bc3d-4352-9ac0-98c01d13189d",
"version": 0,
"groups": [
{
"internalName": "Admin group",
"fields": [
{
"internalName": "Is verified",
"uiProperties": {
"isShow": true
}
},
{
"internalName": "Hide",
"uiProperties": {
"isHide": false
}
},
...
]
},
...
]
},
{
"id": "2b7bbebd-bc3d-4352-9ac0-98c01d13189d",
"version": 0,
"groups": [
{
"internalName": "User group",
"fields": [
{
"internalName": "Is verified",
"uiProperties": {
"isShow": true
}
},
{
"internalName": "Blocked",
"uiProperties": {
"isBlocked": true
}
},
...
]
},
...
]
},
...
]

字段的内部名称可以重复。我想按 group.field.internalName 进行分组并剪切数组(用于分页)并获得如下输出:

{
"totalCount": 3,
"items": [
{
"internalName": "Blocked"
},
{
"internalName": "Hide"
},
{
"internalName": "Is verified"
}
]}

我编写了一个有效的查询,

db.layouts.aggregate(
{
$unwind : "$groups"
},
{
$unwind : "$groups.fields"
},
{
$group: {
"_id" : {
"internalName" : "$groups.fields.internalName",
},
"internalName" : {
$first : "$groups.fields.internalName"
}
}
},
{
$group: {
"_id" : null,
"items" : {
$push : "$$ROOT"
},
"totalCount" : {
$sum : 1
}
}
},
{
$project: {
"items" : {
$slice : [ "$items", 0, 20 ]
},
"totalCount": 1
}
})

但我在将其转换为 java api 时遇到问题。请注意,我需要使用 mongoTemplate 方法。这是我所拥有的以及令我震惊的地方

    final List<AggregationOperation> aggregationOperations = new ArrayList<>();
aggregationOperations.add(unwind("groups"));
aggregationOperations.add(unwind("groups.fields"));

aggregationOperations.add(
group("groups.fields.internalName")
.first("groups.fields.internalName").as("internalName")
);

aggregationOperations.add(
group()
.push("$$ROOT").as("fields")
.sum("1").as("totalCount") // ERROR only string ref can be placed, but i need a number?
);

aggregationOperations.add(
project()
.andInclude("totalCount")
.and("fields").slice(size, page * size)
);
final Aggregation aggregation = newAggregation(aggregationOperations);
mongoTemplate.aggregate(aggregation, LAYOUTS, FieldLites.class).getMappedResults()

通过这个查询,我遇到了 sum() 的问题,因为我只能通过 api 放置一个字符串引用(但需要一个数字)并且在项目操作中 - 出现异常java.lang.IllegalArgumentException:无效引用“totalCount”!] 根本原因

你能帮我翻译这个查询吗?

最佳答案

您可以使用计数

group()
.push("$$ROOT").as("fields")
.count().as("totalCount")

关于java - Mongodb java驱动程序查询转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47506611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com