F#MongoDB使用带字符串过滤器的查找

时间:2018-08-14 07:31:20

标签: mongodb f#

我在尝试从MongoDB获取一些数据时遇到问题。我的目标是将此C#代码重写为F# C#代码:

 class Program
    {
        static void Main(string[] args)
        {
            var cn = "mongodb://localhost:27017/fsStreamingTest";
            var cPack = new ConventionPack {new CamelCaseElementNameConvention()};
            ConventionRegistry.Register("camel case",cPack,t=>true);

            var dbName = MongoUrl.Create(cn).DatabaseName;
            var client = new MongoClient(cn);
            var db = client.GetDatabase(dbName);
            var collection = db.GetCollection<MClient>("clients");

            var filter = BsonDocument.Parse("{firstName:'Jan'}");
            var response = collection.Find(filter).ToList();

        }
    }

在C#中,您可以选择从字符串组成过滤器。此选项在F#中可用吗? 这就是我现在在F#中拥有的东西

module MongoModule

open System
open MongoDB.Driver
open MongoDB.Bson
open MongoDB.Bson.Serialization.Attributes
open MongoDB.Bson.Serialization.Conventions
open System.Threading
open System.Collections.Generic
open System.Collections


type MongoInsertEntity = {
    FirstName: string;
    MiddleName: string option;
    LastName: string
}

type MongoUpdateEntity = {
    [<BsonId>]
    [<BsonRepresentation(BsonType.ObjectId)>]
    MongoId:string;
    FirstName: string;
    MiddleName: string option;
    LastName: string
}


let connectionString = "mongodb://localhost:27017/fsStreamingTest"
let cPack = new ConventionPack()
cPack.Add(new CamelCaseElementNameConvention())
ConventionRegistry.Register("camel case",cPack,fun t -> true)
let dbName = MongoUrl.Create(connectionString).DatabaseName
let dbClient = new MongoClient(connectionString)
let db = dbClient.GetDatabase(dbName)
let clientCollection = db.GetCollection<MongoInsertEntity>("clients")
let updateClientCollection = db.GetCollection<MongoUpdateEntity>("clients")



let writeItemToDb() =     
    let client = {FirstName="Jan";MiddleName=None;LastName="Valek"}
    let cts = new CancellationTokenSource()
    clientCollection.InsertOne(client)

let getItemFromDB() =
    let filter = BsonDocument.Parse("{}")
    let x = new BsonDocumentFilterDefinition<BsonDocument>(filter):>FilterDefinition<BsonDocument>
    let options = new FindOptions()
    let x1 = FilterDefinition<BsonDocument>.op_Implicit("{firstName:'Jan'}")
    let result = updateClientCollection.Find<MongoUpdateEntity> x1 //unable to compose find command
    let x = result.ToJson
    printfn "%A" x

我正在写mongodb正常工作,但是无法通过文本格式的查询获取数据。我知道可以用其他方式构成过滤器,但是对于内部文档过滤,我希望此选项具有字符串过滤器选项。 在F#中甚至有可能吗?

1 个答案:

答案 0 :(得分:2)

这是工作功能:

let getItemFromDB3() = 
    let filter = BsonDocument.Parse("{firstName:'Jan'}")
    let x2 = BsonDocumentFilterDefinition(filter)
    let something = updateClientCollection.Find<MongoUpdateEntity> (x2)
    let clients = something.ToList<MongoUpdateEntity>()
    let fsList = List.ofSeq(clients)
    fsList |> List.iter (fun c-> printfn "jmeno uzivatele %s" c.FirstName)