Home > OS >  how to sort mongodb document to appear document with certain key value to appear first,
how to sort mongodb document to appear document with certain key value to appear first,

Time:04-26

// i want to appear document with isFeatured:"true" at first

{        "_id": "625c13ea5c5d3f49f152783b",
        "name": "helmet 1",
        "description": "gold",
       
        "category": [
            "helmet"
        ],
        "price": "25000",
        "stock": 25,
        "user": "",
        "isFeatured": true // with this property to come first and "isFeatured:false" later
    }

CodePudding user response:

You can invoke sort on the cursor to sort the documents in myCollection on the isFeatured field in descending order.

db.myCollection.find().sort({ isFeatured: -1 })

Or on aggregation pipeline query

db.myCollection.aggregate([{ $sort: { isFeatured: -1 } }])
  • Related