mongodb 将两个字段合并为一个字段并按新合并的字段排序

q3qa4bjr  于 2023-03-07  发布在  Go
关注(0)|答案(1)|浏览(368)

我有下面的文档(...意味着更多的属性和getter和setter)

@Document
public class Equipment
{
...
private String name;
private String internalManufacturer;
private String externalManufacturer;
...
}

和服务中的此方法,其中传递字段的名称(代码)并设置排序。

private void setSorting(String code)
{
    ...
    List<AggregationOperation> pagedAndSortedQuery= new ArrayList<>(baseQuery);
    SortOperation sortOperation = sort(Sort.Direction.ASC, code);
    if (EquipmentsSortingField.MANUFACTURER.getCode().equals(code))
    {
        sortOperation = sort(sortingDirection, "internalManufacturer", "externalManufacturer");
        pagedAndSortedQuery.add(sortOperation);
    }
}

我想把internalManufacturer和externalManufacturer当作一个字段来排序,因为如果我像在服务中那样做,首先我得到的结果是internalManufacturer排序,然后是externalManufacturer排序。重要的是,如果externalManufacturer为空,internalManufacturer就不为空,反之亦然。
例如,我在数据库中有这个:

Equipment (externalManufacturer: John, internalManufacturer: null)
Equipment (externalManufacturer: null, internalManufacturer: Carlos)
Equipment (externalManufacturer: Ash, internalManufacturer: null)
Equipment (externalManufacturer: null, internalManufacturer: Victor)

用我的代码我得到的设备排序如下:

Equipment (externalManufacturer: null, internalManufacturer: Carlos)
Equipment (externalManufacturer: null, internalManufacturer: Victor)
Equipment (externalManufacturer: Ash, internalManufacturer: null)
Equipment (externalManufacturer: John, internalManufacturer: null)

我喜欢把它们做成这样:

Equipment (externalManufacturer: Ash, internalManufacturer: null)
Equipment (externalManufacturer: null, internalManufacturer: Carlos)
Equipment (externalManufacturer: John, internalManufacturer: null)
Equipment (externalManufacturer: null, internalManufacturer: Victor)

总之,将两个字段都排序,就像它只是一个字段一样。
我该怎么做?先谢了。

2nc8po8w

2nc8po8w1#

您应该使用$addFields(内部和外部制造商的连接版本)生成一个新字段,然后沿着此新字段进行排序。

private void setSorting(String code)
{
    ...
    List<AggregationOperation> pagedAndSortedQuery= new ArrayList<>(baseQuery);
    SortOperation sortOperation = sort(Sort.Direction.ASC, code);
    if (EquipmentsSortingField.MANUFACTURER.getCode().equals(code))
    {
        AddFieldsOperation addFieldsOperation =
            Aggregation.addFields().addFieldWithValue(
                    "manufacturerString",
                    StringOperators.Concat.valueOf(ConditionalOperators.ifNull("internalManufacturer").then("")).concatValueOf(ConditionalOperators.ifNull("externalManufacturer").then(""))
            ).build();
        sortOperation = sort(sortingDirection, "manufacturerString");
        pagedAnsSortedQuery.add(addFieldsOperation);
        pagedAndSortedQuery.add(sortOperation);
    }
}

注意,我已经使用了新字段进行排序,并且还在管道中添加了addField阶段。请测试一下,希望你能理解。

相关问题