在 phoenix/elixir 中使用 mongodb 驱动程序进行深度查询
Deep queries with mongodb driver in phoenix/elixir
我正在使用 https://github.com/ankhers/mongodb 的 mongodb 驱动程序来查询 elixir/phoenix 项目中的 mongodb 数据库。一个简单的查询,例如
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)
没问题,但我想知道如何执行更深入的搜索,因为我有嵌套的 json,例如
{"posts":{"name":"something","attributes":{"aspect":{"and_so_on":"endpoint"}}}}.
那么在这种情况下如何到达 "endpoint"?
你的代码完全不是elixir idiomatic, in the first place. One should not reassign values on each step, we usually use pipes Kernel.|>/2
而是
也就是说,您原来的光标可能写成
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()
或者,更好的是,使用模式匹配
%{"name" => one} =
Mongo.find_one(:mongo, "posts", %{})
one
#⇒ "something"
MongoDB也支持mongo query language in Mongo.find/4
as shown in examples here。要获取嵌套元素,可以这样做:
Mongo.find(:mongo, "posts",
%{"attributes" => %{"aspect" => "and_so_on"}})
我正在使用 https://github.com/ankhers/mongodb 的 mongodb 驱动程序来查询 elixir/phoenix 项目中的 mongodb 数据库。一个简单的查询,例如
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)
没问题,但我想知道如何执行更深入的搜索,因为我有嵌套的 json,例如
{"posts":{"name":"something","attributes":{"aspect":{"and_so_on":"endpoint"}}}}.
那么在这种情况下如何到达 "endpoint"?
你的代码完全不是elixir idiomatic, in the first place. One should not reassign values on each step, we usually use pipes Kernel.|>/2
而是
也就是说,您原来的光标可能写成
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()
或者,更好的是,使用模式匹配
%{"name" => one} =
Mongo.find_one(:mongo, "posts", %{})
one
#⇒ "something"
MongoDB也支持mongo query language in Mongo.find/4
as shown in examples here。要获取嵌套元素,可以这样做:
Mongo.find(:mongo, "posts",
%{"attributes" => %{"aspect" => "and_so_on"}})