Swift 如何访问 MongoDB
Perfect 开源项目 参与 Perfect 开发 Slack 在线协同 MongoDBMongoDB库函数是在mongo-c语言库的基础上封装而成,能够为Swift轻松访问MongoDB服务器提供便利。 该工具库软件包是由Swift软件包管理器编译而来,是 请确保安装并激活了最新版本的Swift 3.0 toolchain。 不同操作系统平台的准备工作OS X该工具包需要通过Homebrew安装mongo-c。 安装Homebrew: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 安装mongo-c: brew install mongo-c Linux确保已经安装了libmongoc。 sudo apt-get install libmongoc 在您的项目里引用MongoDB Driver驱动请在Package.swift增加对该驱动的依存关系。 .Package( url:"https://github.com/PerfectlySoft/Perfect-MongoDB.git",majorVersion: 2,minor: 0 ) 关于如何在您的项目中使用Perfect函数库,详见参考手册《使用Swift软件包管理器编译项目》 快速上手通过以下命令快速克隆一个空白的Perfect项目模板: git clone https://github.com/PerfectlySoft/PerfectTemplate.git cd PerfectTemplate 在Package.swift文件中增加依存关系: let package = Package( name: "PerfectTemplate",targets: [],dependencies: [ .Package(url:"https://github.com/PerfectlySoft/Perfect.git",versions: Version(0,0)..<Version(10,0)),.Package(url:"https://github.com/PerfectlySoft/Perfect-MongoDB.git",0)) ] ) 创建Xcode项目: swift package generate-xcodeproj 从Xcode中打开自动生成的 该项目会编译然后在本地端口8181启动一个服务器。
在您的项目中声明MongoDB请在您的Perfect项目源程序开头声明并导入MongoDB函数库: import MongoDB 创建一个MongoDB数据库连接创建到MongoDB服务器连接时,需要相应的URL,内容是IP或域名,并可选择端口号。 确定具体的连接URL之后,参考以下例子打开连接: let client = try! MongoClient(uri: "mongodb://localhost") 其中“localhost”请自行替换为实际的服务器地址。 定义一个数据库一旦服务器连接成功,即可选择具体数据库: let db = client.getDatabase(name: "test") 定义一个MongoDB集合D请采用以下方式定义和操作MongoDB集合: let collection = db.getCollection(name: "testcollection") 关闭活动的服务器连接一旦服务器连接成功,建议采用 defer { collection.close() db.close() client.close() } 执行检索请使用 let fnd = collection.find(query: BSON()) // 初始化一个空数组用于接收格式化结果 var arr = [String]() // “fnd”被定义为MongoCursor的检索记录游标,是可以遍历的 for x in fnd! { arr.append(x.asString) } 有关MongoDB Collections集合类,请参考MongoDB Collections。 长按二维码关注Perfect 官网 如果需要帮助,请注册我们在Slack上的中文频道: http://perfect.ly/ 更多内容请查看 PerfeclySoft 源码仓库 https://github.com/PerfectlyS... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |