0

Given: Documents looks like this:

Supplier Document

{
    "_id" : "63",
    "companyName" : "Niranjan Company",
    "createdBy" : "niranjank4523@gmail.com",
    "createdOn" : ISODate("2017-07-06T03:12:13.171Z"),
    "active" : true,
        "locations" : [
            "594fbfc9ae0638325796a17c",
            "594fbfc9ae0638325796a17d",
            "594fbfc9ae0638325796a17e"
        ],
        "serviceArea" : "Nationwide",
    },
    "updatedDate" : ISODate("2017-07-24T06:29:42.221Z")
}

Locations document

{
    "_id" : ObjectId("594fbfc9ae0638325796a17c"),
    "location" : "New York"
}

Requirement: Sort the collection in below manner

  1. Supplier documents are sorted by the number of locations.
  2. Locations will be alphbetically sorted.
  3. Supplier with no locations will appear at the end.

Though I am able to sort it by number of locations in it, still unable to resolve the second point of requirement in which I have to furthur sort the data alphabetically on the basis of location and put the suppliers without any locations at the end.

Note: We can not change the structure due to some constraints from the client.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Niranjan Kumar
  • 1,438
  • 1
  • 12
  • 29
  • @Neil: https://stackoverflow.com/questions/13449874/how-to-sort-array-inside-collection-record-in-mongodb is not helping in sorting out my issue. – Niranjan Kumar Jul 25 '17 at 10:11
  • It should. Because the only way you "sort" an array in the aggregation framwork is by using `$unwind` and then `$sort`. Just like the answer there shows you how to do. – Neil Lunn Jul 25 '17 at 10:12
  • Please also do not make trivial edits in an attempt to circumvent duplicates. Removing an aggregation framework tag was not going to automatically reopen your question. It is in fact duplicated in several answers here. – Neil Lunn Jul 25 '17 at 10:18

0 Answers0