search
HomeDatabaseMysql TutorialEnhancing the F# developer experience with MongoDB

This is a guest post by Max Hirschhorn,who is currently an intern at MongoDB. About the F# programming language F# is a multi-paradigm language built on the .NET framework. It isfunctional-first and prefers immutability, but also supportso

This is a guest post by Max Hirschhorn, who is currently an intern at MongoDB.

About the F# programming language

F# is a multi-paradigm language built on the .NET framework. It is functional-first and prefers immutability, but also supports object-oriented and imperative programming styles.

Also, F# is a statically-typed language with a type inference system. It has a syntax similar to Ocaml, and draws upon ideas from other functional programming languages such as Erlang and Haskell.

Using the existing .NET driver

The existing .NET driver is compatible with F#, but is not necessarily written in a way that is idiomatic to use from F#.

Part of the reason behind this is that everything in F# is explicit. For example, consider the following example interface and implementing class.

[]
type I =
    abstract Foo : unit -> string
type C() =
    interface I with
        member __.Foo () = "bar"
// example usage
let c = C()
(c :> I).Foo()

So in order to use any of the interface members, the class must be upcasted using the :> operator. Note that this cast is still checked at compile-time.

In a similar vein, C# supports implicit operators, which the BSON library uses for converting between a primitive value and its BsonValue equivalent, e.g.

new BsonDocument {
    { "price", 1.99 },
    { "$or", new BsonDocument {
        { "qty", new BsonDocument { { "$lt", 20 } } },
        { "sale", true }
    } }
};

whereas F# does not. This requires the developer to explicitly construct the appropriate type of BsonValue, e.g.

BsonDocument([ BsonElement("price", BsonDouble(1.99))
               BsonElement("$or", BsonArray([ BsonDocument("qty", BsonDocument("$lt", BsonInt32(20)))
                                              BsonDocument("sale", BsonBoolean(true)) ])) ])

with the query builder, we can hide the construction of BsonDocument instances, e.g.

Query.And([ Query.EQ("price", BsonDouble(1.99))
            Query.OR([ Query.LT("qty", BsonInt32(20))
                       Query.EQ("sale", BsonBoolean(true)) ]) ])

It is worth noting that the need to construct the BsonValue instances is completely avoided when using a typed QueryBuilder.

type Item = {
    Price : float
    Quantity : int
    Sale : bool
}
let query = QueryBuilder()
query.And([ query.EQ((fun item -> item.Price), 1.99)
            query.Or([ query.LT((fun item -> item.Quantity), 20)
                       query.EQ((fun item -> item.Sale), true) ]) ])

What we are looking for is a solution that matches the brevity of F# code, offers type-safety if desired, and is easy to use from the language.

New features

The main focus of this project is to make writing queries against MongoDB as natural from the F# language as possible.

bson quotations

We strive to make writing predicates as natural as possible by reusing as many of the existing operators as possible.

A taste

Consider the following query

{ price: 1.99, $or: [ { qty: { $lt: 20 } }, { sale: true } ] }

we could express this with a code quotation

bson  x?price = 1.99 && (x?qty 

or with type safety

bson  x.Price = 1.99 && (x.Quantity 
Breaking it down

The quotations are not actually executed, but instead are presented as an abstract syntax tree (AST), from which an equivalent BsonDocument instance is constructed.

The ? operator

The ? operator is defined to allow for an unchecked comparison. The F# language supports the ability to do a dynamic lookup (get) and assignment (set) via the ? and ? operators respectively, but does not actually provide a implementation.

So, the F# driver defines the ? operator as the value associated with a field in a document casted to a fresh generic type.

// type signature: BsonDocument -> string -> 'a
let (?) (doc : BsonDocument) (field : string) =
    unbox doc.[field]

and similarly defines the ? operator as the coerced assignment of a generically typed value to the associated field in the document.

// type signature: BsonDocument -> string -> 'a -> unit
let (? ignore
Queries

Unchecked expressions have the type signature Expr<bsondocument> bool></bsondocument>.

// $mod
bson  x?qty % 4 = 0 @>

Checked expressions have the type signature Expr bool>.

// $mod
bson  x.Quantity % 4 = 0 @>
Updates

Unchecked expressions have the type signature Expr<bsondocument> unit list></bsondocument>. The reason for the list in the return type is to perform multiple update operations.

// $set
bson  [ x?qty 
// $inc
bson  [ x?qty 
Mmm… sugar

A keen observer would notice that (+) 1 is not an int, but actually a function int -> int. We are abusing the fact that type safety is not enforced here by assigning the quantity field of the document to a lambda expression, that takes a single parameter of the current value.

Note that

// $inc
bson  [ x?qty 

is also valid.

Checked expressions either have the type signature Expr unit list> or Expr 'DocType>, depending on whether the document type has mutable fields (only matters for record types).

// $set
bson  [ x.Quantity 
// $inc
bson  [ x.Quantity 

mongo expressions

Uses the monadic structure (computation expression) to define a pipeline of operations that are executed on each document in the collection.

Queries
let collection : IMongoCollection = ...
mongo {
    for x in collection do
    where (x?price = 1.99 && (x?qty 
<p>or with a typed collection</p>
<pre class="brush:php;toolbar:false">
let collection : IMongoCollection = ...
mongo {
    for x in collection do
    where (x.price = 1.99 && (x.qty 
<h5 id="Updates">Updates</h5>
<pre class="brush:php;toolbar:false">
let collection : IMongoCollection = ...
mongo {
    for x in collection do
    update
    set x?price 0.99
    inc x?qty 1
}

or with a typed collection

let collection : IMongoCollection = ...
mongo {
    for x in collection do
    update
    set x.Price 0.99
    inc x.Quantity 1
}

Serialization of F# data types

Now supports

  • record types
  • option types
  • discriminated unions

Conclusion

Resources

The source code is available at GitHub. We absolutely encourage you to experiment with it and provide us feedback on the API, design, and implementation. Bug reports and suggestions for improvements are welcomed, as are pull requests.

Disclaimer. The API and implementation are currently subject to change at any time. You must not use this driver in production, as it is still under development and is in no way supported by MongoDB, Inc.

Acknowledgments

Many thanks to the guidance from the F# community on Twitter, and my mentors: Sridhar Nanjundeswaran, Craig Wilson, and Robert Stam. Also, a special thanks to Stacy Ferranti and Ian Whalen for overseeing the internship program.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
2 个月不见,人形机器人 Walker S 会叠衣服了2 个月不见,人形机器人 Walker S 会叠衣服了Apr 03, 2024 am 08:01 AM

机器之能报道编辑:吴昕国内版的人形机器人+大模型组队,首次完成叠衣服这类复杂柔性材料的操作任务。随着融合了OpenAI多模态大模型的Figure01揭开神秘面纱,国内同行的相关进展一直备受关注。就在昨天,国内"人形机器人第一股"优必选发布了人形机器人WalkerS深入融合百度文心大模型后的首个Demo,展示了一些有趣的新功能。现在,得到百度文心大模型能力加持的WalkerS是这个样子的。和Figure01一样,WalkerS没有走动,而是站在桌子后面完成一系列任务。它可以听从人类的命令,折叠衣物

THE是什么币种,THE币值得投资吗?THE是什么币种,THE币值得投资吗?Feb 21, 2024 pm 03:49 PM

THE是什么币种?THE(TokenizedHealthcareEcosystem)是一种数字货币,利用区块链技术,专注于医疗健康行业的创新和改革。THE币的使命是利用区块链技术提高医疗行业的效率和透明度,推动各方之间更高效的合作,包括患者、医护人员、制药公司和医疗机构。THE币的价值和特点首先,THE币作为一种数字货币,具备了区块链的优势——去中心化、安全性高、交易透明等,让参与者能够信任和依赖这个系统。其次,THE币的独特之处在于它专注于医疗健康行业,借助区块链技术改造了传统医疗体系,提升了

Developer Proxy是什么? Developer Proxy怎么下载?Developer Proxy是什么? Developer Proxy怎么下载?Jul 03, 2023 pm 08:37 PM

微软日前发布了一款名为DeveloperProxy的命令行工具,目前已经更新至0.9预览版本,该软件可用于测试软件调用HTTPAPI的行为,避免开发者向用户请求过多权限,可预防软件的过度授权问题。DeveloperProxy工具能够抓取应用所发出的一系列MicrosoftGraphAPI请求,并可以自动检测应用程序需要调用的API数量。微软表示,这些权限比较工作会在本地端进行,因此用户的数据不会被上传到外界。当工具检测到应用程序拥有的权限,超过应用实际需要的权限时,便会向开发者发出相关警告,此时

如何查询The Sandbox币最新价格?如何查询The Sandbox币最新价格?Mar 05, 2024 am 11:52 AM

如何查询TheSandbox币最新价格TheSandbox是建立在以太坊区块链上的去中心化游戏平台,使用其原生代币SAND可以购买土地、资产和游戏体验。想要查询SAND最新价格的步骤如下:选择一个可靠的价格查询网站或应用程序。一些常用的价格查询网站包括:CoinMarketCap:https://coinmarketcap.com/Coindesk:https://www.coindesk.com/币安:https://www.binance.com/在网站或应用程序中搜索SAND。查看SAND

如何查询The Graph币最新价格?如何查询The Graph币最新价格?Mar 05, 2024 am 09:55 AM

如何查询TheGraph币最新价格?TheGraph是一个去中心化的协议,旨在为区块链数据提供高效的索引和查询服务。该协议的设计使得开发人员能够更轻松地构建和推出分散式应用程序(dApp),并让这些应用程序能够便捷地访问区块链数据。要查询TheGraph币(GRT)的最新价格,您可以按照以下步骤操作:选择一个可靠的价格查询网站或应用程序。一些常用的价格查询网站包括:CoinMarketCap:https://coinmarketcap.com/Coindesk:https://www.coind

如何查看The Graph币市值?如何查看The Graph币市值?Mar 13, 2024 pm 10:43 PM

如何查看TheGraph币市值TheGraph是一种去中心化的协议,旨在帮助开发者索引和查询区块链数据。其代币GRT被用于支付网络费用和奖励节点运营商。查看TheGraph币市值的方法:选择一个可靠的网站或平台:有多个网站和平台提供加密货币市值信息,例如CoinMarketCap、CoinGecko、非小号等。选择一个可靠的网站或平台很重要,以确保您获得准确的信息。搜索TheGraph:在网站或平台上搜索GRT或TheGraph。查看市值:TheGraph的市值通常会在搜索结果中显示。提示:市值

罗技企业桌面配置白皮书罗技企业桌面配置白皮书Jul 24, 2024 pm 01:54 PM

最近读了罗技在上半年出品的企业桌面配置白皮书,涉及到的企业级桌面外设的知识面和选购逻辑,给了我们非常多的启发。其中许多新鲜的观点,非常适合与中关村的老粉们分享。罗技白皮书:桌面外设采购新思考罗技作为桌面外设领域的佼佼者,其品牌实力和技术创新有目共睹。白皮书发布时间的意义罗技白皮书的发布时机恰逢企业办公模式转型之际。混合办公模式的普及对雇主品牌和人才吸引提出了新挑战。桌面外设采购新趋势以往的桌面外设采购标准可能过于简化。不同岗位员工对键盘、鼠标、耳机和摄像头的需求差异显著。罗技白皮书中的观点罗技白

三星折叠屏新品曝光 预计 7 月下旬亮相三星折叠屏新品曝光 预计 7 月下旬亮相Mar 21, 2024 pm 02:16 PM

三星计划在今年下半年推出新一代GalaxyZFold与Flip6系列折叠屏智能手机。近期,韩国媒体TheElec和《时事周刊e》透露了关于这两款新品更多的细节。三星GalazyZFold6爆料图片。图源@chunvn8888据TheElec报道,三星电子的供应链厂商预计于5月初启动GalaxyZFold6和Flip6相关组件的生产工作,相比之下,去年GalaxyZFold5和Flip5的零件生产始于5月下半月。这意味着今年的标准版GalaxyZ系列发布时间表相较于上年提前了约两周至三周的时间。去

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software