F
F
Fedor2011-03-22 18:14:33
NoSQL
Fedor, 2011-03-22 18:14:33

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.

  1. {
  2.    "firstname": "Vasya",
  3.    "lastname": "Pupkin",
  4.    "created": 1300125070,
  5.    "ban": 0,
  6.    "posts": {
  7.     {
  8.        "title": "Hello!",
  9.        "post": "post post post",
  10.        "created": 1300125370,
  11.        "hash": "523343633a2fac703e84a3c6afcb3a8a",
  12.        "client_ip": "127.0.0.1"
  13.     },
  14.     {
  15.        "title": "Hello again!",
  16.        "post": "post post post",
  17.        "created": 1300125870,
  18.        "hash": "523343633a2fac703e84a3c6afcb3a8a",
  19.        "client_ip": "127.0.0.1"
  20.     }
  21.   }
  22. }



Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sajgak, 2011-03-22
@FFF

sort(array("posts.created" => -1))
should work if I understand you correctly

C
carbonariy, 2011-03-22
@carbonariy

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

F
Fedor, 2011-03-22
@FFF

I also “smeared” everything by default, but with nested documents it looks prettier and, in theory, it should be more convenient to work with them :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question