无法使用MongoDB的LINQ表达式重载。驱动器包含ProjectionDefinition

时间:2018-10-31 01:56:14

标签: mongodb linq f# .net-core

我很难尝试使用F#在MongoDB数据库中进行聚合。我已经构建了这个小的示例代码来说明:

open System
open MongoDB.Driver
open MongoDB.Bson

type MyDocument =
    { Id  : BsonObjectId
      Foo : string
      Bar : int
      Baz : bool
      Quz : DateTime }

[<EntryPoint>]
let main _ =
    let client = new MongoClient("mongodb://localhost:27017/faggregate")
    let db = client.GetDatabase("faggregate")
    let collection = db.GetCollection<MyDocument>("aggregations")

    let documents = collection.Aggregate().Group(Builders<MyDocument>.Projection.Include(fun x -> x.Foo))

    0

此卡在:

No overloads match for method 'Include'. The available overloads are shown below.
member Include: 
   field: FieldDefinition<MyDocument> 
       -> ProjectionDefinition<MyDocument>

但是ProjectionDefinitionBuilderpublic ProjectionDefinition<TSource> Include(Expression<Func<TSource, object>> field)

有没有人能够在F#上使用MongoDB聚合?

2 个答案:

答案 0 :(得分:1)

op_Implicit是关键!在MongoDB文档上看到ProjectionDefinition可以从普通的字符串(JSON-ones)创建,但是在F#上,应使用implicit显式调用此op_Implicit运算符。所以...

let group = ProjectionDefinition<MyDocument,_>.op_Implicit("""{ _id: "$Foo"}""")
let documents = collection.Aggregate().Group(group)

像魅力一样工作,我可以像在纯Mongo中一样编写聚合

答案 1 :(得分:0)

在阅读Leo的答案之后,我学习了MongoDB文档,并且有一种更干净的方法,使我感到很舒服,可以使用PipelineDefinition.Create()创建管道。此方法接受array<string>,并带有要添加的阶段,如下面的示例中(我使用Json语法)。然后可以在Aggregate方法中使用它:

let aggregation = PipelineDefinition.Create([|
        "{'$match': { 'communityEventId': '" + communityEventId + "'}}";
        """
            {
                '$lookup': {
                    'from': '_User',
                    'localField': 'email',
                    'foreignField': 'username',
                    'as': 'user'
                }
            }
        """;
        """
            {
                '$unwind': {
                    'path': '$user',
                    'preserveNullAndEmptyArrays': true
                }
            }
        """;
        """
            {
                '$addFields': {
                    'userId': '$user._id'
                }
            }
        """;
        """
            {
                '$project': {
                    'user': 0
                }
            }
        """
    |])

collection.Aggregate(aggregation).ToList()

就您而言,您可以为Foo创建$ match。

https://mongodb.github.io/mongo-csharp-driver/2.5/apidocs/html/T_MongoDB_Driver_PipelineDefinition_2.htm