datanoise / mongo.cr

Crystal binding for MongoDB C Driver
MIT License
97 stars 35 forks source link

Would be nice to have a folder for some examples? #27

Open elrok123 opened 7 years ago

elrok123 commented 7 years ago

Hey, I was just wondering if anyone could possibly write an examples directory for this, so that we can actually see how to use this properly. There's seems to be a lot of little details getting in the way of using this effectively without a lot of mongoc lib knowledge. Also having to dig around in the codebase and guess what to do with a lot of the stuff is a bit of a nightmare.

vectorselector commented 6 years ago

basic stuff even... like there's almost no crystal lang resources on BSON.to_json implementation- how to even use json mapping at least or?

(if not json, how to access values? is there some special syntax to drill into BSON?)

i was too stupid to be able to understand how to use your libBSON wrapper "to_json" as it asked for c stuff like length etc...

a basic crud example would help mongo-land immensely, as i am generally finding this wrapper and the driver work great and more help would enable more usage which will help stabilize and entrench it as a tool, I suppose.

fwiw, I later discovered that I can access fields as such <%= field["name"] %> but I'm not sure how to drill any deeper.

Pyroglyph commented 5 years ago

I did some fiddling today and managed to construct some BSON objects and insert them into a DB successfully.

BSON.from_json accepts a JSON string and returns a BSON object. This seems to be the simplest way to go if the object you want to work with is either already a JSON string or can be easily converted to JSON.

BSON.new creates an empty BSON object. You can manually add fields like so: bson["field_name"] = "example string" This seems to support most common types and also other BSON documents. Arrays are added like this:

# there is probably an easier way but I haven't looked into it enough yet
bson.append_array("array_name") do |array|
  your_array.each do |element|
    array << element
  end
end

That should be enough to get you going.