Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Aggregation - Does $unwind order documents the same way as the nested array order

I am wandering whether using $unwind operator in aggregation pipeline for document with nested array will return the deconstructed documents in the same order as the order of the items in the array. Example: Suppose I have the following documents

{ "_id" : 1, "item" : "foo", values: [ "foo", "foo2", "foo3"] }
{ "_id" : 2, "item" : "bar", values: [ "bar", "bar2", "bar3"] }
{ "_id" : 3, "item" : "baz", values: [ "baz", "baz2", "baz3"] }

I would like to use paging for all values in all documents in my application code. So, my idea is to use mongo aggregation framework to:

  1. sort the documents by _id
  2. use $unwind on values attribute to deconstruct the documents
  3. use $skip and $limit to simulate paging

So the question using the example described above is:

Is it guaranteed that the following aggregation pipeline:

[
    {$sort: {"_id": 1}},
    {$unwind: "$values"}
]

will always result to the following documents with exactly the same order?:

{ "_id" : 1, "item" : "foo", values: "foo" }
{ "_id" : 1, "item" : "foo", values: "foo2" }
{ "_id" : 1, "item" : "foo", values: "foo3" }
{ "_id" : 2, "item" : "bar", values: "bar" }
{ "_id" : 2, "item" : "bar", values: "bar2" }
{ "_id" : 2, "item" : "bar", values: "bar3" }
{ "_id" : 3, "item" : "baz", values: "baz" }
{ "_id" : 3, "item" : "baz", values: "baz2" }
{ "_id" : 3, "item" : "baz", values: "baz3" }
like image 978
Aleydin Karaimin Avatar asked Oct 26 '25 07:10

Aleydin Karaimin


2 Answers

I also asked the same question in the MongoDB community forum . An answer that confirms my assumption was posted from a member of MongoDB stuff.

Briefly:

Yes, the order of the returned documents in the example above will always be the same. It follows the order from the array field.

like image 191
Aleydin Karaimin Avatar answered Oct 29 '25 00:10

Aleydin Karaimin


In the case that you do run into issues with order. You could use includeArrayIndex to guarantee order.

[
 {$unwind: {
   path: 'values',
   includeArrayIndex: 'arrayIndex'
 }},
 {$sort: {
   _id: 1,
   arrayIndex: 1
 }},
 { $project: {
    index: 0
 }}
]
like image 36
GitGitBoom Avatar answered Oct 28 '25 22:10

GitGitBoom