Answer the question
In order to leave comments, you need to log in
Sorting nested documents in MongoDB?
Hello!
I'm using MongoDB in one of my projects and want to redesign the database, more compactly, using nested documents. Got a question. Let's say there is a collection with a large number of such documents:
Actually, the main question with sorting, how can you select the last post by posts.created from all records of all users? How to sort documents by nested fields? I did not find a clear answer in the documentation. It would seem that everything is beautiful and convenient, but sorting breaks off such a structure.
Tell me, who had experience with MongoDB, how are these things solved?
Thank you.
Answer the question
In order to leave comments, you need to log in
sort(array("posts.created" => -1))
should work if I understand you correctly
If posts are added to the end each time they are created, then take the last element of the array. If they are updated, delete and add to the end with each update
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question