.Net6 + GraphQL + MongoDb 实现Query过滤(查询)功能

介绍

Query返回数据我们已经看完了,这里我们将如果筛选数据,给查询加上条件

正文

修改Program

builder.Services
    .AddGraphQLServer()
    .AddQueryType<PostQuery>()
    .AddMongoDbFiltering()
    .AddMongoDbProjections();

修改PostQuery.cs

   public class PostQuery
    {
        [UseProjection]
        [UseFiltering]
        public IExecutable<Post> GetPosts([Service] DbContext db)
        { 
            
            return db.Post.AsExecutable();
        }
    }

这时候我们去https://localhost:7145/graphql/调用的接口.加上where条件

query testGetPost {
  posts(where: {
      title: { eq: "1 - introduction to graphql" }
    }) {
    id
    title
    comments {
      name
    }
  }
}

我们看下mongodb的监控信息,已经对我们的where做出了变化

{
    "op": "query",
    "ns": "GQL_Example.post",
    "command": {
        "find": "post",
        "filter": {
            "Title": {
                "$eq": "1 - introduction to graphql"
            }
        },
        "sort": {
            "Title": NumberInt("1")
        },
        "projection": {
            "Comments.Name": NumberInt("1"),
            "Title": NumberInt("1"),
            "_id": NumberInt("1")
        },
        "$db": "GQL_Example",
        "lsid": {
            "id": UUID("3b2fc182-6821-4216-96a3-d3db42350015")
        },
        "$clusterTime": {
            "clusterTime": Timestamp(1676094001, 1),
            "signature": {
                "hash": BinData(0, "AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                "keyId": NumberLong("0")
            }
        }
    }
}

结语

本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用

联系作者:加群:867095512 @MrChuJiu

posted @ 2023-02-13 20:42  初久的私房菜  阅读(11721)  评论(0编辑  收藏  举报
作者:初久的私房菜
好好学习,天天向上
返回顶部小火箭
好友榜:
如果愿意,把你的博客地址放这里
张弛:https://blog.zhangchi.fun/