最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

.net - how to write a Mongo Aggregation query using AggregateFluent in C# - Stack Overflow

programmeradmin1浏览0评论

I want to write a C# code for the below mongo aggregation query

[
  {
    $match: {
       uid: "8c08e94d-57f0-4b63-a232-58399070db66"
    }
  },
  {
    $project: {
      _id: 0,
      custId: {
        $filter: {
          input: "$aas",
          as: "itemM",
          cond: {
            $eq: [
              "$$itemM.aty",
              "ABC"
            ]
          }
        }
      },
      loginId: {
        $filter: {
          input: "$aas",
          as: "itemW",
          cond: {
            $eq: ["$$itemW.aty", "XYZ"]
          }
        }
      }
    }
  },
  {
    $unwind: "$custId"
  },
  {
    $unwind: "$loginId"
  },
  {
    $project: {
      _id: 0,
      oid: "$custId.aid",
      lid: "$loginId.aid"
    }
  },
  {
    $lookup: {
      from: "device",
      let: {
        oid: "$oid",
        lid: "$lid"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: ["$id", "$$oid"]
                },
                {
                  $eq: ["$loginId", "$$lid"]
                },
                {
                  $eq: ["$trusted", true]
                }
              ]
            }
          }
        }
      ],
      as: "devices"
    }
  }
]

I am trying to join User collection with Device collection and wan to use the AggregateFluent strongly typed approach to accomplish this and not the BsonDocument approach. I have the EntityMapping c# classes as UserDocument and DeviceDocument in my project and want to generate an output from this query which will be of type UserDeviceDocument as below:

public class UserDeviceDocument : UserDocument 
{ 
    public List<DeviceDocument> Devices { get; set; } 
}

Can some one suggest how to write this using C# mongo driver

I tried doing it as follows:

var pipeline = new EmptyPipelineDefinition<UserDocument>();
var findResult = await userCollection.AggregateAsync(pipeline.Match(u => u.UniversalId == uId)
    .Project(user => new
    {
        loginId = user.aas.Where(a => a.aty== "XYZ").Select(a => a.aid),
        opaId = user.aas.Where(a => a.aty== "XYZ").Select(a => a.aid),
    })
    .Unwind("$loginId")
    .Unwind("$opaId")
    .Project(p => new
    {
        lid = "$loginId",
        oid = "$oapId"
    })
    .Lookup(
        deviceCollection,
        let: new BsonDocument
        {
            { "opaId1", "$oid" },
            { "loginId1", "$lid" }
        },
        lookupPipeline: new EmptyPipelineDefinition<DeviceDocument>()
        .Match(dp => dp.OpaqueId == "$opaId1" &&
        dp.LoginId == "$loginId1" && dp.Trusted == true),
        @as: (UserDeviceDocument ud) => ud.Devices
        )
    )
    .ContinueWith(predicate=>predicate.Result.ToListAsync())
    .Unwrap()
    .ConfigureAwait(false);

this gives me the below error :

System.AggregateException
  HResult=0x80131500
  Message=One or more errors occurred. (Command aggregate failed: FieldPath field names may not start with '$'. Consider using $getField or $setField..)
  Source=System.Private.CoreLib
  StackTrace:
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at MongoDB.MongoDbOutboundFunction.<>c.<ExecuteAggregateUserDeviceTagOperationAsync>b__53_5(Task`1 predicate) in C:\RepositoriesMongoDB\MongoDbOutboundFunction.cs:line 1982
   at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
   at System.Threading.Tasks.Task.<>c.<tor>b__272_0(Object obj)
   at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
发布评论

评论列表(0)

  1. 暂无评论