D
D
diman912014-10-14 21:49:25
MongoDB
diman91, 2014-10-14 21:49:25

Sorting in MongoDB?

Hello. I've been scratching my head with sorting for a day now. There is a document:

user:{ 
  type: Schema.ObjectId, 
  ref: 'User',
  required: true,
  index: true
},
title:{
  type: String
},
txt:{
  type: String
},
created:{
  type: Date,
  default: Date.now
},
reposts: [{
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    index: true
  },
  created: {
    type: Date,
    default: Date.now
  }
}]

You need to display all posts and reposts of the user sorted by date, own posts are sorted by the date the post itself was created, and reposts by the date the repost was created.
For example:
a = {
  user:"Вася",
  title:"Привет",
  txt:"Привет мир",
  created:"29-10-2014",
  reposts:[]
}
b = {
  user:"Вася",
  title:"Привет",
  txt:"Привет мир",
  created:"29-11-2014",
  reposts:[]
}
c = {
  user:"Петя",
  title:"Привет",
  txt:"Привет мир",
  created:"29-09-2014",
  reposts:[
    user:"Вася",
    created:"29-12-2014"
  ]
}
b = {
  user:"Вася",
  title:"Привет",
  txt:"Привет мир",
  created:"25-11-2014",
  reposts:[]
}

Vasya's posts/reposts should be sorted like this: c,b,d,a
I'd be glad for any advice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2014-10-15
@lega

Store reposts as separate documents (with a link to the original if necessary), then both the index and the query will be simple.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question