I am using the mongodb driver from https://github.com/ankhers/mongodb to query a mongodb database in an elixir/phoenix project. A simple query such as
cursor = Mongo.find(:mongo, "posts",%{})
list = Enum.to_list(cursor)
object= Enum.fetch(list,0)
object= elem(object, 1)
new_list=Map.fetch(object, "name")
new_list=elem(new_list,1)
new_cursor= Mongo.find(:mongo, "posts",%{"name" => new_list})
new_list=Enum.to_list(new_cursor)
is no problem, but I am wondering how to perform deeper searches as I have nested jsons such as
{"posts":{"name":"something","attributes":{"aspect":{"and_so_on":"endpoint"}}}}.
So how to get to "endpoint" in this case ?
Your code is extremely not elixir idiomatic, in the first place. One should not reassign values on each step, we usually use pipes Kernel.|>/2
instead.
That said, your original cursor might be written as
list =
:mongo
|> Mongo.find("posts", %{})
|> Enum.fetch(0)
|> elem(1)
|> Map.fetch("name")
|> elem(1)
new_list =
:mongo
|> Mongo.find("posts", %{"name" => list})
|> Enum.to_list()
or, better, with pattern matching
%{"name" => one} =
Mongo.find_one(:mongo, "posts", %{})
one
#⇒ "something"
MongoDB also supports mongo query language in Mongo.find/4
as shown in examples here. To get to the nested element one might do:
Mongo.find(:mongo, "posts",
%{"attributes" => %{"aspect" => "and_so_on"}})