简体   繁体   English

在 F# 中投影来自 MongoDb Find 的结果

[英]Projecting results from MongoDb Find in F#

I'm trying to query MongoDB using MongoDB.Driver and return a partial result using mongo projection.我正在尝试使用MongoDB.Driver查询 MongoDB 并使用 mongo 投影返回部分结果。

I've figured out how to query without projection, but not a partial result.我已经想出了如何在没有投影的情况下进行查询,但不是部分结果。 This is my function for finding results:这是我查找结果的功能:

let Find<'a> collectionName (filterDefinition: FilterDefinition<'a>) =
    let collection = database.GetCollection<'a> collectionName
    collection.Find(filterDefinition).ToEnumerable() |> List.ofSeq

This is an example of how I call it:这是我如何称呼它的一个例子:

let findByIdFilter id =
    Builders<MyModel>.Filter.Eq((fun s -> s.id), id)

let results = Find collectionName (findByIdFilter id)

Let's say my model is something like that:假设我的模型是这样的:

type MyInnerModel = {
    zInner: bool
}

type MyModel = {
    id: ObjectId
    x: int
    y: double
    z: MyInnerModel
}

And these are my projections:这些是我的预测:

type MyModelProjection1 = {
    id: ObjectId
    y: double
}

type MyModelProjection1 = {
    id: ObjectId
    x: int
    z: MyInnerModel
}

How do I construct my queries for following scenarios:我如何为以下场景构建我的查询:

  • Find documents matching (fun (m: MyModel) -> mzzInner = false) with projection to MyModelProjection1查找匹配(fun (m: MyModel) -> mzzInner = false)并投影到MyModelProjection1
  • Find documents matching (fun (m: MyModel) -> mx = 5) with projection to MyModelProjection2查找匹配(fun (m: MyModel) -> mx = 5)并投影到MyModelProjection2
  • Find ALL documents with projection to MyModelProjection1 or MyModelProjection2查找投影到MyModelProjection1MyModelProjection2所有文档

You can define your projections like so:您可以像这样定义您的投影:

let projection1 =
    Builders<MyModel>.Projection.Expression(fun model ->
        { id = model.id; y = model.y })

let projection2 =
    Builders<MyModel>.Projection.Expression(fun model ->
        { id = model.id; x = model.x; z = model.z })

You can then use them in the following way:然后,您可以通过以下方式使用它们:

    let one =
        collection
            .Find(fun m -> m.z.zInner = false)
            .Project(projection1).ToEnumerable() |> List.ofSeq

    let two =
        collection
            .Find(fun m -> m.x = 5)
            .Project(projection2).ToEnumerable() |> List.ofSeq

    let three =
        collection
            .Find(fun _ -> true)
            .Project(projection1).ToEnumerable() |> List.ofSeq

    let four =
        collection
            .Find(fun _ -> true)
            .Project(projection1).ToEnumerable() |> List.ofSeq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM