This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

mongodb order by list

By: zulius on Jun 28th, 2011  |  syntax: JavaScript  |  size: 1.67 KB  |  views: 137  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. use foo;
  2. db.foo.ensureIndex({bar: 1});
  3. db.foo.save({ bar: 12});
  4. db.foo.save({ bar: 57});
  5. db.foo.save({ bar: 33});
  6. db.foo.save({ bar: 7});
  7. db.foo.save({ bar: 101});
  8. db.foo.find({});
  9. /*
  10. { "_id" : ObjectId("4e0a0e4e708f107ecdf9aae0"), "bar" : 12 }
  11. { "_id" : ObjectId("4e0a0e52708f107ecdf9aae1"), "bar" : 57 }
  12. { "_id" : ObjectId("4e0a0e55708f107ecdf9aae2"), "bar" : 33 }
  13. { "_id" : ObjectId("4e0a0e5a708f107ecdf9aae3"), "bar" : 7 }
  14. { "_id" : ObjectId("4e0a0e5d708f107ecdf9aae4"), "bar" : 101 }
  15. */
  16.  
  17. /* a wild guess at querying/sorting by a list syntax. fails. */
  18. db.foo.find({bar : { $in: [101, 7, 12, 57] } }).sort({bar: [101, 7, 12, 57]});
  19. /*
  20. { "_id" : ObjectId("4e0a0e5a708f107ecdf9aae3"), "bar" : 7 }
  21. { "_id" : ObjectId("4e0a0e4e708f107ecdf9aae0"), "bar" : 12 }
  22. { "_id" : ObjectId("4e0a0e52708f107ecdf9aae1"), "bar" : 57 }
  23. { "_id" : ObjectId("4e0a0e5d708f107ecdf9aae4"), "bar" : 101 }
  24. */
  25.  
  26. /* ... and querying/sorting by ObjectId would be really nice too */
  27. db.foo.find({_id :
  28. { $in: [
  29.     ObjectId("4e0a0e5d708f107ecdf9aae4"), /* 101 */
  30.     ObjectId("4e0a0e5a708f107ecdf9aae3"), /* 7 */
  31.     ObjectId("4e0a0e4e708f107ecdf9aae0"), /* 12 */
  32.     ObjectId("4e0a0e52708f107ecdf9aae1")] /* 57 */
  33. }}).sort(
  34. { _id: [
  35.     ObjectId("4e0a0e5d708f107ecdf9aae4"), /* 101 */
  36.     ObjectId("4e0a0e5a708f107ecdf9aae3"), /* 7 */
  37.     ObjectId("4e0a0e4e708f107ecdf9aae0"), /* 12 */
  38.     ObjectId("4e0a0e52708f107ecdf9aae1")] /* 57 */
  39. });
  40. /*
  41. { "_id" : ObjectId("4e0a0e5a708f107ecdf9aae3"), "bar" : 7 }
  42. { "_id" : ObjectId("4e0a0e4e708f107ecdf9aae0"), "bar" : 12 }
  43. { "_id" : ObjectId("4e0a0e52708f107ecdf9aae1"), "bar" : 57 }
  44. { "_id" : ObjectId("4e0a0e5d708f107ecdf9aae4"), "bar" : 101 }
  45. */
clone this paste RAW Paste Data