【问题标题】:Spring Boot MongoDb return items from Document list conditionallySpring Boot MongoDb 有条件地从文档列表中返回项目
【发布时间】:2022-12-19 21:10:42
【问题描述】:

我有一个看起来像下面的 JSON 对象的 mongo 文档。我想做的是,使用 mongoDb 查询生成器,返回用户 1 的所有已读图书:false。

例如:

var query = new Query();
query.addCriteria(Criteria.where("id").is(1));
query.fields().elemMatch("books", Criteria.where("read").is(false));

返回用户 1 和第一本未读的书,但我想要未读框的完整列表。

Users:[
  {
    id: 1,
    name: 'John Doe',
    books: [
      {
        id: 1,
        title: 'The Hobbit',
        read: false
      },
      {
        id: 2,
        title: 'The Lord of the Rings',
        read: false
      },
      {
        id: 3,
        title: 'The Silmarillion',
        read: false
      }
    ]
  },
  {
    id: 2,
    name: 'Jane Doe',
    books: []
  }
}

【问题讨论】:

    标签: mongodb spring-boot aggregation-framework spring-data-mongodb


    【解决方案1】:

    您可以在聚合管道中将 filter 与项目阶段一起使用。

    db.collection.aggregate([
      {
        $match: {
          "id": 1
        }
      },
      {
        $project: {
          "books": {
            $filter: {
              input: "$books",
              as: "b",
              cond: {
                $eq: ["$$b.read",false]
              }
            }
          }
        }
      }
    ])
    

    Mongo Playground

    查询转换为管道的这个项目阶段。

    AggregationOperation matchStage = Aggregation
                    .match(Criteria.where("id").is(1));
    
    AggregationOperation projectStage = Aggregation.project()
                    .and(ArrayOperators.Filter
                            .filter("books")
                            .as("b")
                            .by(Eq.valueOf("read").equalToValue(false)))
                    .as("books");
    
    mongoTemplate.aggregate(
        Aggregation.newAggregation(matchStage, projectStage), 
        Collection.class,   //collection class
        Collection.class    //return type class
    ).getMappedResults();
    

    【讨论】:

    • 您将如何仅限于用户 1?
    • 更新以添加匹配阶段。
    • “返回类型类”会是 Book.class 吗?遗憾的是没有返回任何结果。
    【解决方案2】:

    我犹豫是否要添加它,因为它不使用查询构建器,但这里是使用存储库接口和@Aggregation 管道的解决方案

    public interface UserRepository extends MongoRepository<Users, Long> {
        @Aggregation(pipeline = {
            "{'$match':{'id': ?0 }}",
            "{'$project': {'books':  1}}",
            "{'$unwind': { path:'$books'}}",
            "{'$match':{'books.read': ?1 }}",
        })
        List<Book> findByUserIdAndRead(Long id, boolean read);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2022-10-25
      • 1970-01-01
      • 2017-03-08
      • 2016-04-26
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      相关资源
      最近更新 更多