0

how to sort a subdocument in mongodb with mongooes? here is data below i would like to sort

[
  {
      "_id": "5eacbb21936a0e07e8aa8f7e",
      "users": [
          {
              "_id": "5eae29e207b6bf06f856aeec",
              "name": "crystal",
              "number": 20
          },
          {
              "_id": "5eae29e207b6bf06f856aeec",
              "name": "barbra",
              "number": 40
          },
          {
              "_id": "5eae29e207b6bf06f856aeec",
              "name": "marry",
              "number": 30
          }
      ],

      "__v": 0
  }
]

i tried this

db.aggregate([{$match: {"_id": ObjectId("5eacbb21936a0e07e8aa8f7e") }}, {$sort: { "user.number": -1 }}])

and also this but none of the two is working

db.find({"_id": ObjectId("5eacbb21936a0e07e8aa8f7e") }).sort({"user.number": -1})

i would like to instead get this result below but the query is returning the same data as above

[
  {
      "_id": "5eacbb21936a0e07e8aa8f7e",
      "users": [
          {
              "_id": "5eae29e207b6bf06f856aeec",
              "name": "crystal",
              "number": 20
          },
           {
              "_id": "5eae29e207b6bf06f856aeec",
              "name": "marry",
              "number": 30
          },
          {
              "_id": "5eae29e207b6bf06f856aeec",
              "name": "barbra",
              "number": 40
          },
      ],

      "__v": 0
  }
]
manny
  • 347
  • 5
  • 19

2 Answers2

1

Try This query

 db.demo2.aggregate([
 {$match: {"_id": ObjectId("5eacbb21936a0e07e8aa8f7e") }},{$unwind:"$users"},
 {$sort: { "users.number": -1 }},   
 {"$group" : {_id:"$_id",
    users:{ $push: "$users" }}
 }
])
Mahesh Bhatnagar
  • 1,042
  • 1
  • 7
  • 8
  • 1
    I feel I must note that this account has posted several answers recently which are basically lifted from existing answers. Finding existing answers on StackOverflow and then posting them as your own is not how this is done. Answers which basically consist of "Try this" and a block of code with no explanation, generally present as something obtained from another source rather than the direct knowledge of the person posting the answer. – Neil Lunn Nov 03 '19 at 10:40
-1

There is a typo.

the field name is users not user.

just change it and it will work:

db.collectionName.aggregate([{$match: {"_id": ObjectId("5eacbb21936a0e07e8aa8f7e") }}, {$sort: { "users.number": -1 }}])

or

db.collectionName.find({"_id": ObjectId("5eacbb21936a0e07e8aa8f7e") }).sort({"users.number": -1})
niranjan_harpale
  • 2,048
  • 1
  • 17
  • 21