Mongo DB 查询 shell 到 Mongo 驱动程序构建器

问题描述 投票:0回答:0

我在将基于 shell 的查询转换为等效的 mongo 驱动程序生成器时遇到一些问题。

我有以下有效的 shell 脚本

[
  {
    $match:
      /**
       * query: The query in MQL.
       */
      {
        _id: ObjectId("64c76edfeb2dd2291a501f88"),
      },
  },
   {
     $unset: [
       "_id",
       "deleted",
       "createdAt",
       "tenantId",
     ],
   },
  {
    $lookup:
      /**
       * from: The target collection.
       * localField: The local join field.
       * foreignField: The target join field.
       * as: The name for the results.
       * pipeline: Optional pipeline to run on the foreign collection.
       * let: Optional variables to use in the pipeline field stages.
       */
      {
        from: "User",
        localField: "usersId",
        foreignField: "_id",
        as: "result",
      },
  },
  {
    $unset: ["usersId", "name"],
  },
  {
    $unwind: {
      path: "$result",
      preserveNullAndEmptyArrays: false,
    },
  },
  {
    $set:
      /**
       * field: The field name
       * expression: The expression.
       */
      {
        usersId: null,
        _id: "$result._id",
        createdAt: "$result.createdAt",
        deleted: "$result.deleted",
        name: "$result.name",
        surname: "$result.surname",
        email: "$result.email",
        birthDate: "$result.birthDate",
        tenants: "$result.tenants",
        roles: "$result.roles",
      },
  },
]

我尝试编写以下驱动程序生成器:

//GetUsersByWorkspaceQuery 
            var pipeline = PipelineDefinition<Workspace, User>.Create(new IPipelineStageDefinition[] {

              PipelineStageDefinitionBuilder.Match(Builders<Workspace>.Filter.ElemMatch(w => w.Id, workspaceId)),

              PipelineStageDefinitionBuilder.Lookup<Workspace, User, User>(foreignCollection: _database.GetCollection<User>(nameof(User)),
                   localField: a => a.UsersId,
                   foreignField: b => b.Id,
                   @as: c => "$result"),

              PipelineStageDefinitionBuilder.Unwind<User>("result") 

 var result = await _database.GetCollection<Workspace>(nameof(Workspace)).Aggregate(pipeline).ToListAsync();

但我有一个运行时异常。

The output type to the last stage was expected to be Domain.Entities.User, but was MongoDB.Bson.BsonDocument. (Parameter 'stages')

另外,我没有找到我在驱动程序生成器的 shell 中使用的方法设置/取消设置

问题是什么? ,我该怎么办?

谢谢

我希望构建一个 mongo 驱动程序生成器,其结果与我使用 shell 查询得到的结果相同

这里是请求实体 https://www.noelshack.com/2023-31-3-1690964795-sheme-mongo.png request entities

c# mongodb mongodb-query mongodb-.net-driver
© www.soinside.com 2019 - 2024. All rights reserved.