code.king
code.king

Reputation: 378

How to sort mongo collection on the basis array/ object type field

Hi I'm newbie in mongodb I want to sort collection on the basis of field which is an array/object for example a user can have many cars,

{
  "_id" : ObjectId("5a7428a4408437d7155bbde7"),
  "firstName" : "some user",
  "lastName" : "some user",
  "phone" : some_phone,
  "__v" : 0,
  "cars" : {
  "car_id_1" : {
    "_id" : "5a741201408437d7155bbdcd",
        "name" : "1st vehicle",
        "vNumber" : "4tvechicle",
        "maxCapacity" : 34

},
"car_id_2" : {
    "_id" : "5a7412bc408437d7155bbdde",
        "name" : "2nd vehicle",
        "vNumber" : "78opsd",
        "maxCapacity" : 54

  }
  }
 }

In this case this user has two cars how can I sort on the basis of who has maximum cars

Upvotes: 1

Views: 40

Answers (1)

Saravana
Saravana

Reputation: 12817

if you are using mongo v3.4+ you can try below aggregation pipeline

$objectToArray to convert cars to array and $size to get the cars array size

db.cols.aggregate(
  [
    {$addFields: {count : {$size : {$ifNull : [{$objectToArray : "$cars"}, []]}}}},
    {$sort: {count : -1 }}
  ]
)

Upvotes: 1

Related Questions