如何在 Lua 程式設計中使用 lua-mongo 庫?


Lua 提供了不同的庫,可用於處理 MongoDB。最流行的框架,使我們能夠在 Lua 中使用 MongoDB,是 **lua-mongo**。

**Lua-mongo** 是 MongoDB C 驅動程式的 Lua 繫結 -

  • 它為 MongoDB 命令、**CRUD** 操作和 MongoDB C 驅動程式中的 GridFS 提供了 **統一** 的 API。
  • 為了方便起見,從 Lua/JSON 到 BSON 的透明轉換。
  • 根據 Lua 數字的容量,自動在 Lua 數字和 BSON Int32、Int64 和 Double 型別之間進行轉換,而不會丟失精度(當 Lua 允許時)。手動轉換也可使用。

您可以使用以下命令下載 MongoDB -

luarocks install lua-mongo

MongoDB 設定

為了使以下示例按預期工作,我們需要初始資料庫設定。假設條件如下所示。

  • 您已安裝並設定了 MongoDB,並將 /data/db 資料夾用於儲存資料庫。
  • 您已建立了一個名為 **lua-mongo-test** 的資料庫和一個名為 test 的集合。

匯入 MongoDB

假設您的 Lua 實現已正確完成,我們可以使用簡單的 require 語句匯入 MongoDB 庫。

local mongo = require 'mongo'

變數 **mongo** 將透過引用主 MongoDB 集合來提供對函式的訪問。

現在我們已完成設定,讓我們編寫一個示例,在該示例中,我們將瞭解如何使用 lua-mongo 框架在 Lua 中使用不同的 MongoDB 查詢。

示例

請考慮以下示例 -

local mongo = require 'mongo'
local client = mongo.Client('mongodb://127.0.0.1')
local collection = client:getCollection('lua-mongo-test', 'test')
-- Common variables
local id = mongo.ObjectID()
collection:insert{_id = id, name = 'John Smith', age = 50}
collection:insert{_id = id, name = 'Mukul Latiyan', age = 24}
collection:insert{_id = id, name = 'Rahul', age = 32}
for person in collection:find({}, {sort = {age = -1}}):iterator() do
   print(person.name, person.age)
end

在上面的示例中,我們試圖以降序對 MongoDB 集合中存在的不同條目的影像進行排序。

輸出

John Smith 50
Rahul 32
Mukul Laityan 24

更新於: 20-Jul-2021

867 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告