代码之家  ›  专栏  ›  技术社区  ›  Chechy Levas

MongoDb和F#:如何获取集合中字段的最小值和最大值?

  •  0
  • Chechy Levas  · 技术社区  · 5 年前

    我使用的是(在编写本文时)最新版本(2.8)的C#MongoDb驱动程序。我用的是F。我想得到一个字段的最小值和最大值。

    关于如何使用F中的MongoDb(最新版本)似乎没有太多内容,所以如果我遗漏了一些东西,我很抱歉。

            let client = new MongoClient(connString)
            let db = client.GetDatabase("AirQuality")
            let col = db.GetCollection<ReadingValue>("ReadingValue")
            let toDictionary (map : Map<_, _>) : Dictionary<_, _> = Dictionary(map)
    
            let minb = ["$min", "$ReadingDate"] |> Map.ofList |> toDictionary
            let maxb = ["$max", "$ReadingDate"] |> Map.ofList |> toDictionary
            let grpb = 
                [
                    "_id", null
                    "min", minb
                    "max", maxb
                ] |> Map.ofList |> toDictionary
    
            let aggb = ["$group", grpb] |> Map.ofList |> toDictionary
            let doc = new BsonDocument(aggb)
            let pl = new BsonDocumentPipelineStageDefinition<ReadingValue,string>(doc)
            let epl = new EmptyPipelineDefinition<ReadingValue>()
            let finalPipeline = epl.AppendStage(pl)
    
            use result = col.Aggregate(finalPipeline)
    

    但会引发运行时错误 Cannot deserialize a 'String' from BsonType 'Document'.

    顺便说一句,我很惊讶使用F#中的MongoDb有多尴尬。

    关闭后编辑:

    这个问题是关于如何在F#中完成任务。问题 linked to 迎合其他语言(可能是mongoshell)。在F#中使用这些技术(据我所知)是不可能的。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Tarmil    5 年前

    至少可以使用 dict

    let grpb =
        dict [
            "_id", null
            "min", dict ["$min", "$ReadingDate"]
            "max", dict ["$max", "$ReadingDate"]
        ]
    let aggb = new BsonDocument(dict ["$group", grpb])
    
        2
  •  0
  •   Chechy Levas    5 年前

    我让它来处理这个

        type MinMax = {_id:obj; min:string; max:string}
    
        let client = new MongoClient(connString)
        let db = client.GetDatabase("AirQuality")
        let col = db.GetCollection<ReadingValue>("ReadingValue")
        let toDictionary (map : Map<_, _>) : Dictionary<_, _> = Dictionary(map)
    
        let minb = ["$min", "$ReadingDate"] |> Map.ofList |> toDictionary
        let maxb = ["$max", "$ReadingDate"] |> Map.ofList |> toDictionary
        let grpb = 
            [
                "_id", null
                "min", minb
                "max", maxb
            ] |> Map.ofList |> toDictionary
    
        let aggb = ["$group", grpb] |> Map.ofList |> toDictionary |> (fun x -> new BsonDocument(x))
    
        let pl = new BsonDocumentPipelineStageDefinition<ReadingValue,MinMax>(aggb)
    
        let epl = new EmptyPipelineDefinition<ReadingValue>()
        let finalPipeline = epl.AppendStage(pl)
        use result = col.Aggregate(finalPipeline)
        let minMax = result.ToList() |> Seq.head
    

    但我觉得这很难看。难道没有更简单的方法吗?