find.lua

local MongoClient = require("mongorover.MongoClient")
local client = MongoClient.new("mongodb://localhost:27017/")
local exampleDatabase = client:getDatabase("exampleDB")
local exampleCollection = exampleDatabase:getCollection("exampleCollection")

-- Drop database to get a clean slate for this example.
exampleCollection:drop()

-- After the insert, there should be three documents.
local arrayOfDocuments = {{color = "blue"}, {color = "blue"}, {color = "red"}}
exampleCollection:insert_many(arrayOfDocuments)
print("number of documents in collection", exampleCollection:count({}))

-- Using MongoCollection:find_one(...) I can find one document who has the color blue
local result = exampleCollection:find_one({color = "blue"})

-- The result is a table that has the color and the _id generated by MongoDB inside.
print("color of document", result.color)
print("_id generated by MongoDB", result._id)

-- To find all documents that have the color blue, use MongoCollection:find(...)
-- To choose which fields get returned, use the fields parameter to suppress fields.

local results = exampleCollection:find({color = "blue"}, {_id = false, color = true})
for result in results do
	print("color of document", result.color)
	print("_id suppressed, so it is nil", result._id)
end


---- This is the output of this script.

-- number of documents in collection	3
-- color of document	blue
-- _id generated by MongoDB	ObjectID("55a01f28d2b38b2b2135e981")
-- color of document	blue
-- _id suppressed, so it is nil	nil
-- color of document	blue
-- _id suppressed, so it is nil	nil
generated by LDoc 1.4.3 Last updated 2015-09-16 03:55:02