-3

Suppose this is a collection named books in mongodb and the data are as follows.Here I ignore _id. please provide a simple query for finding all books from database where the most costly book's document will comes first.

>{
    "name":"A",
    "cost":100
 }
 {
    "name":"B",
    "cost":1000
 }
 {
    "name":"F",
    "cost":400
 }
 {
    "name":"E",
    "cost":400
 }
 {
    "name":"Z",
    "cost":800
 }

My expected result will be:

>{
     "name":"B",
     "cost":1000
 }
 {
     "name":"Z",
     "cost":800
 }
 {
     "name":"E",
     "cost":400
 }
 {
     "name":"F",
     "cost":400
 }
 {
     "name":"A",
     "cost":100
 }
Koushik Mondal
  • 865
  • 7
  • 15

2 Answers2

0

please use : .sort({cost:-1}) in your query for showing decending order of collection.

Full query will be :

For node.js :

books.find({}).sort({"cost":-1}).exec(function(err,data){

})

or

db.books.find().sort({"cost":-1})
Md Nazmul Hossain
  • 2,768
  • 5
  • 26
  • 49
0

Try This

  db.books.find({},{"name":1,_id:0,"cost":1}).sort({"cost":-1})
Wasiq Muhammad
  • 3,080
  • 3
  • 16
  • 29