4

如何从 MongoDB 转换元组

{'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}

列出来

[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]
4

4 回答 4

4

假设您想基本上将元组的两个连续元素组合在一起,这并不太难。您可以使用element\2从元组中提取元素。并tuple_size\1获得元组的大小。这里有几种处理方法:

1> Tup = {'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}.
{'_id',<<"vasya">>,password,<<"12ghd">>,age,undefined}
2> Size = tuple_size(Tup).            
6

您可以为此使用列表推导:

3> [{element(X, Tup), element(X+1, Tup)} || X <- lists:seq(1, Size, 2)].
[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]

或者你可以压缩它:

4> lists:zip([element(X, Tup) || X <- lists:seq(1, Size, 2)], [element(X, Tup) || X <- lists:seq(2, Size, 2)]).
[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]

您可以通过创建一个处理拉出元素的函数来清理该拉链。

slice(Tuple, Start, Stop, Step) ->
    [element(N, Tuple) || N <- lists:seq(Start, Stop, Step)].

然后调用这个函数:

5> lists:zip(slice(Tup, 1, Size, 2), Slice(Tup, 2, Size, 2)).
[{'_id',<<"vasya">>},{password,<<"12ghd">>},{age,undefined}]
于 2013-05-29T15:19:27.637 回答
1

您可以使用bson:fields/1 ( https://github.com/mongodb/bson-erlang/blob/master/src/bson.erl#L52 )。bson是mongodb erlang驱动的依赖

于 2013-05-30T08:49:54.983 回答
0

或者,您可以编写一个简单的函数来执行此操作:

mongo_to_proplist(MongoTuple) ->
    mongo_to_tuple(MongoTuple, 1, tuple_size(MongoTuple)).

mongo_to_proplist(Mt, I, Size) when I =:= Size -> [];
mongo_to_proplist(Mt, I, Size) ->
    Key = element(I, Mt),
    Val = element(I+1, Mt),
    [{Key,Val}|mongo_to_proplist(Mt, I+2, Size)].

这基本上是列表理解版本正在做的事情,但被分解成一个显式循环。

于 2013-05-29T22:16:47.653 回答
0

效率不高,所以不要在大型​​结构上使用它,但非常简单:

to_proplist(Tuple) -> to_proplist1(tuple_to_list(Tuple), []).

to_proplist1([], Acc) -> Acc;
to_proplist1([Key, Value | T], Acc) -> to_proplist1(T, [{Key, Value} | Acc]).

如果由于某些奇怪的原因顺序很重要,请在 to_proplist1/2 的基本情况下反转 proplist。

于 2013-05-30T07:20:09.193 回答