0

I am currently using "spring-boot-starter-data-mongodb" for persisting documents to a collection in mongodb. The document contains a List with nested objects like:

{
 foo:bar,
 foos: [
  {
   foo1: bar1,
   foo2: bar2
  },
  {
   foo1: bar4,
   foo2: bar3
  }
 ]
}

The mapping of these documents consist the following:

private String foo;
private List<Foo> foos;

Foo:

private String foo1;
private String foo2;

The business logic is heavily depending on the order of the foos (the List elements).

The real questions are:

  • Are inserting a document preserves the order of the elements, so that the first item in the list will be the first in the JSON and so on?
  • Are querying preserves the order of the elements, so if an element is the N-th member of the document in the DB, will it be the N-th element in the mapped object as well?

Currently it seems to be true but I need to make sure it is guaranteed.

1 Answers1

0

Yes, AFAIK the sort is guaranteed because MongoDB stores the document as it is. The document is stored and there is no reason to modify values from the array when read it.

Also, there are a couple questions here in StackOverflow like:

So as seen before, assuming MongoDB preserves the order of elements within an array, when querying the collection in Spring Data MongoDB the returned documents will be mapped to the corresponding objects.

So the order of elements in the List of your object will be the same as the order of the elements in the array into MongoDB document.

J.F.
  • 13,927
  • 9
  • 27
  • 65
  • In my understanding Mongo keeps the order (as the questions above state), but I can not find any written confirmation on that when Spring Data MongoDB maps the List in the same order (tests are showing this should be true, but since critical business logic depends on it it must be 100% sure). I think it should be depending on the Mongo driver used by the library. Anyway the safest (and probably better) solution would be to introduce some property for programmatically ordering the returned list so even if the driver does not return in order, business logic will correct it. – Ágoston Székely Jan 23 '23 at 09:45