How to make Mongo.find return a document as a list of tuples to preserve order #204
-
BSON documents have fields in a specific order. As much as I understand, when I use The README says about data representation:
Maybe I don't understand the above well, but I expected to get How could I preserve order as stored in the database? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Why do you expect to get an ordered list of key-value pairs? The documents are represented as maps. You send and receive the documents as maps. Why do you need the order of keys? In this case, you can just use a list with key-values embedded in a document like this:
But to be honest I don't understand the requirements. |
Beta Was this translation helpful? Give feedback.
-
Hey Rodolfo, I understand now. Currently, it is not supported. In the encoder, the list of attributes is converted into a map like this: defp doc_fields("", acc) do
acc |> Enum.reverse() |> Enum.into(%{})
end You see, the driver has the order of keys, but unfortunately, it gets lost by converting it into a map. I can imagine, that I can add an option like defp doc_fields("", acc) do
acc
|> Map.new()
|> Map.put(:order, Enum.map(acc, fn {key, _value} -> key end))
end In this case, each document contains an attribute The new extension Since this requirement seems to be very rare, I need to add some code to make sure that the performance of the encoder is not affected without this option. Still, a good opportunity to take another look at the decoder and encoder for some improvements. 😀 |
Beta Was this translation helpful? Give feedback.
-
I provided a PR #211 The solution is, that you define a decoder module that preserves the order. Feel free to test it. |
Beta Was this translation helpful? Give feedback.
Hey Rodolfo,
I understand now. Currently, it is not supported. In the encoder, the list of attributes is converted into a map like this:
You see, the driver has the order of keys, but unfortunately, it gets lost by converting it into a map. I can imagine, that I can add an option like
preserve_order: :order
to turn the code into:In this case, each document contains an attribute
:order
that includes a list of keys in the original order. I cannot change the result of the encoder because…