Question

I have a mongo collection:

/* 0 */
{
  "_id" : ObjectId("51f1fcc08188d3117c6da351"),
  "cust_id" : "abc123",
  "ord_date" : ISODate("2012-10-03T18:30:00Z"),
  "status" : "A",
  "price" : 25,
  "items" : [{
      "sku" : "ggg",
      "qty" : 7,
      "price" : 2.5
    }, {
      "sku" : "ppp",
      "qty" : 5,
      "price" : 2.5
    }]
}

/* 1 */
{
  "_id" : ObjectId("51fa1c318188d305fcbf9f9b"),
  "cust_id" : "abc123",
  "ord_date" : ISODate("2012-10-03T18:30:00Z"),
  "status" : "A",
  "price" : 27,
  "items" : [{
      "sku" : "ggg",
      "qty" : 7,
      "price" : 2.5
    }, {
      "sku" : "ppp",
      "qty" : 5,
      "price" : 2.5
    }]
}

When I am giving the aggregate query for sorting in ascending order:

 db.orders.aggregate([{
     "$unwind": "$items"
 }, {
     "$sort": {
         "price": -1
     }
 }, {
     "$match": {}
 }, {
     "$group": {
         "price": {
             "$first": "$price"
         },
         "items": {
             "$push": {
                 "sku": "$items.sku"
             }
         },
         "_id": "$_id"
     }
 }, {
     "$project": {
         "_id": 0,
         "price": 1,
         "items": 1
     }
 }])

I get result:

{
    "result": [{
        "price": 25,
        "items": [{
            "sku": "ggg"
        }, {
            "sku": "ppp"
        }]
    }, {
        "price": 27,
        "items": [{
            "sku": "ggg"
        }, {
            "sku": "ppp"
        }]
    }]
}

i.e it is sorting in ascending order and vice versa.

Was it helpful?

Solution

Move the $sort after $group, since the previous sort will be lost after grouping.

 db.orders.aggregate([{
     "$unwind": "$items"
 }, {
     "$match": {}
 }, {
     "$group": {
         "price": {
             "$first": "$price"
         },
         "items": {
             "$push": {
                 "sku": "$items.sku"
             }
         },
         "_id": "$_id"
     }
 }, {
     "$sort": {
         "price": -1
     }
 }, {
     "$project": {
         "_id": 0,
         "price": 1,
         "items": 1
     }
 }])

For $natural operator, this is the quoted from the doc.

The $natural operator uses the following syntax to return documents in the order they exist on disk

Long story short, that means the order you see is not necessarily consistent with the order it store in DB.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top