Enhancing 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.
原文地址:Enhancing the F# developer experience with MongoDB, 感谢原作者分享。

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











기계력 보고서 편집자: 우신(Wu Xin) 국내판 휴머노이드 로봇+대형 모델팀이 옷 접기 등 복잡하고 유연한 재료의 작업 작업을 처음으로 완료했습니다. OpenAI 멀티모달 대형 모델을 접목한 Figure01이 공개되면서 국내 동종업체들의 관련 진전이 주목받고 있다. 바로 어제, 중국의 "1위 휴머노이드 로봇 주식"인 UBTECH는 Baidu Wenxin의 대형 모델과 긴밀하게 통합되어 몇 가지 흥미로운 새로운 기능을 보여주는 휴머노이드 로봇 WalkerS의 첫 번째 데모를 출시했습니다. 이제 Baidu Wenxin의 대형 모델 역량을 활용한 WalkerS의 모습은 이렇습니다. Figure01과 마찬가지로 WalkerS는 움직이지 않고 책상 뒤에 서서 일련의 작업을 완료합니다. 인간의 명령을 따르고 옷을 접을 수 있습니다.

THE(Tokenized Healthcare Ecosystem)는 블록체인 기술을 사용하여 의료 산업의 혁신과 개혁에 초점을 맞춘 디지털 통화입니다. THE 코인의 임무는 블록체인 기술을 사용하여 의료 산업의 효율성과 투명성을 향상시키고 환자, 의료진, 제약 회사 및 의료 기관을 포함한 모든 당사자 간의 보다 효율적인 협력을 촉진하는 것입니다. THE Coin의 가치와 특징 우선, THE Coin은 디지털 화폐로서 블록체인의 장점(분권화, 높은 보안성, 투명한 거래 등)을 갖고 있어 참여자들이 이 시스템을 신뢰하고 의존할 수 있습니다. 둘째, THE 코인의 독창성은 의료 및 건강 산업에 초점을 맞추고 블록체인 기술을 사용하여 전통적인 의료 시스템을 변화시키고 개선한다는 것입니다.

Microsoft는 최근 Preview 버전 0.9로 업데이트된 DeveloperProxy라는 명령줄 도구를 출시했습니다. 이 소프트웨어는 개발자가 사용자에게 너무 많은 권한을 요청하는 것을 방지하고 소프트웨어의 과도한 인증을 방지하기 위해 HTTP API를 호출하는 소프트웨어의 동작을 테스트하는 데 사용할 수 있습니다. . DeveloperProxy 도구는 애플리케이션에서 발행한 일련의 Microsoft Graph API 요청을 캡처하고 애플리케이션이 호출해야 하는 API 호출 수를 자동으로 감지할 수 있습니다. Microsoft는 이러한 권한 비교가 로컬에서 수행되므로 사용자 데이터가 외부 세계에 업로드되지 않을 것이라고 말했습니다. 도구가 애플리케이션에 실제로 필요한 것보다 더 많은 권한이 있음을 감지하면 개발자에게 관련 경고를 표시합니다.

TheSandbox 코인의 최신 가격을 확인하는 방법 TheSandbox는 Ethereum 블록체인을 기반으로 구축된 분산형 게임 플랫폼으로, 자체 토큰 SAND를 사용하여 토지, 자산 및 게임 경험을 구매할 수 있습니다. SAND의 최신 가격을 확인하는 방법은 다음과 같습니다. 믿을 수 있는 가격 확인 웹사이트나 앱을 선택하세요. 일반적으로 사용되는 가격 쿼리 웹사이트는 다음과 같습니다: CoinMarketCap: https://coinmarketcap.com/Coindesk: https://www.coindesk.com/Binance: https://www.binance.com/ 웹사이트나 SAND 앱에서 검색하세요. 모래보기

TheGraph 코인의 최신 가격을 확인하는 방법은 무엇입니까? TheGraph는 블록체인 데이터에 대한 효율적인 인덱싱 및 쿼리 서비스를 제공하도록 설계된 분산형 프로토콜입니다. 이 프로토콜은 개발자가 분산형 애플리케이션(dApp)을 보다 쉽게 구축 및 실행할 수 있도록 하고 이러한 애플리케이션에 블록체인 데이터에 대한 편리한 액세스를 제공하도록 설계되었습니다. TheGraph Coin(GRT)의 최신 가격을 확인하려면 다음 단계를 따르세요. 신뢰할 수 있는 가격 확인 웹사이트나 앱을 선택하세요. 일반적으로 사용되는 가격 쿼리 웹사이트는 다음과 같습니다: CoinMarketCap: https://coinmarketcap.com/Coindesk: https://www.coind

TheGraph 코인 시가총액을 확인하는 방법 TheGraph는 개발자가 블록체인 데이터를 색인화하고 쿼리할 수 있도록 설계된 분산형 프로토콜입니다. 토큰인 GRT는 네트워크 수수료를 지불하고 노드 운영자에게 보상하는 데 사용됩니다. TheGraph 통화의 시장 가치를 확인하는 방법: 신뢰할 수 있는 웹사이트 또는 플랫폼을 선택하십시오. CoinMarketCap, CoinGecko, Feixiaohao 등과 같이 암호화폐 시장 가치 정보를 제공하는 여러 웹사이트와 플랫폼이 있습니다. 정확한 정보를 얻으려면 신뢰할 수 있는 웹사이트나 플랫폼을 선택하는 것이 중요합니다. TheGraph 검색: 웹사이트나 플랫폼에서 GRT 또는 TheGraph를 검색하세요. 시가총액 보기: TheGraph의 시가총액은 검색 결과에 자주 표시됩니다. 팁: 시가총액

최근 로지텍이 상반기에 제작한 기업용 데스크탑 구성 백서를 읽었는데, 기업용 데스크탑 주변기기에 관한 지식과 구매 논리가 우리에게 많은 영감을 주었습니다. 이러한 신선한 관점 중 다수는 중관촌의 오랜 팬들과 공유하기에 매우 적합합니다. 로지텍 백서: 데스크탑 주변 장치 구매에 대한 새로운 생각 데스크탑 주변 장치 분야의 선두주자로서 로지텍의 브랜드 강점과 기술 혁신은 모두에게 분명합니다. 백서 공개 시기의 중요성 로지텍 백서 공개 시기는 기업 오피스 모델의 변화와 일치한다. 하이브리드 사무실 모델의 인기는 고용주 브랜딩 및 인재 유치에 새로운 과제를 제기합니다. 데스크탑 주변 장치 구매의 새로운 추세 이전 데스크탑 주변 장치 구매 표준은 너무 단순했을 수 있습니다. 다양한 직위에 있는 직원들은 키보드, 마우스, 헤드셋, 카메라에 대한 요구 사항이 상당히 다릅니다. 로지텍 백서의 관점 Logitech White

삼성전자는 올 하반기 차세대 폴더블폰 '갤럭시Z폴드'와 '플립6' 시리즈를 출시할 예정이다. 최근 국내 매체 더일렉과 '지지위클리e'는 이들 두 가지 신제품에 대한 자세한 내용을 공개했다. 삼성 갤럭시 Z 폴드6의 사진이 유출됐습니다. 출처@chunvn8888 디일렉에 따르면 삼성전자 공급망 제조사들은 갤럭시Z폴드6·플립6 관련 부품 생산을 5월 초부터 시작할 것으로 예상된다. 반면 갤럭시Z폴드5·플립5 부품 생산은 2월부터 시작될 전망이다. 지난해 5월 중순. 올해 갤럭시Z 시리즈 스탠다드 버전 출시 일정이 지난해보다 2~3주 정도 빨라진 셈이다. 가다
