使用微aut数据查询mongoDb内嵌文档



使用Micronaut数据执行以下操作

  1. 查找具有id和子类别id的项目
  2. 根据类别id和子类别更新子类别项id
  3. 删除基于类别id和sub的子类别项类别id

我有下面的数据结构

{
        "id": "625a8d1a23c8feb3234fbf28",
        "name": "Category 1",
        "description": "Category 1 description",
        "subCategory": [{
                "id": "625a8d6fe0e3cff6e8a3b795",
                "name": "Sub Category 1",
                "description": "Sub Category 1 description"
            },
            {
                "id": "625a8d782672979b1482f5ca",
                "name": "Sub Category 2",
                "description": "Sub Category 2 description"
            }
        ]
    }

在micronaut中有一个自定义查询生成器,如下所述https://micronaut-projects.github.io/micronaut-data/latest/guide/#mongoCustomQueries和https://micronaut-projects.github.io/micronaut-data/latest/guide/#mongoCriteriaExecuteQuery

@Introspected
public record SubCategorySpecification() {
    public static PredicateSpecification<Category> categoryAndSubCategoryIdEquals(ObjectId categoryId, ObjectId subCategoryId) {
        return (root,criteriaBuilder) -> {
            criteriaBuilder.equal(root.get("id"), categoryId);
            return criteriaBuilder.and(criteriaBuilder.equal(root.get("subCategory.id"), subCategoryId));
        };
    }
}

我尝试了上面的代码,并得到了一个异常作为Cannot query entity [Category] on non-existent property: subCategory.id,不确定如何使用 @ MongoFindQuery 编写自定义查询

您可能需要将子类别定义为嵌入式才能正确识别。

可以定义自定义查询:

   @MongoFindQuery("{ $and: [{"_id": :categoryId}, {"subCategory.id": :subCategoryId}]")
   List<Category> customFind(ObjectId categoryId, ObjectId subCategoryId);

类似地,您可以使用@MongoUpdateQuery@MongoDeleteQuery。有关语法,请查看官方MongoDB文档。

最新更新