soubhagya pradhan
soubhagya pradhan

Reputation: 547

Mongodb sorting issue

My mongodb collection:

  [{
    "_id" : ObjectId("5dd6598d55396f36052e347d"),
    "isActive" : true,
    "myarray" : [
        {
            "my_id" : "5d967d08821b4031a197b002",
            "name" : "jack"
        },
        {
            "my_id" : "5d967d2c821b4031a197b003",
            "name" : "manison"
        }
    ]
  },
  {
    "_id" : ObjectId("5dd6598d55396f36052e347d"),
    "isActive" : true,
    "myarray" : [
        {
            "my_id" : "5d967d08821b4031a197b002",
            "name" : "penelope"
        },
        {
            "my_id" : "5d967d2c821b4031a197b003",
            "name" : "cruz"
        }
    ]
  }]

Here i am trying to sort based on the name. not expecting to sort inside the array but expecting outside.

Expecting result be like

[{
  "_id" : ObjectId("5dd6598d55396f36052e347d"),
  "isActive" : true,
  "myarray" : [
    {
      "my_id" : "5d967d08821b4031a197b002",
      "name" : "penelope"
    },
    {
      "my_id" : "5d967d2c821b4031a197b003",
      "name" : "cruz"
    }
  ]
},{
  "_id" : ObjectId("5dd6598d55396f36052e347d"),
  "isActive" : true,
  "myarray" : [
    {
      "my_id" : "5d967d08821b4031a197b002",
      "name" : "jack"
    },
    {
      "my_id" : "5d967d2c821b4031a197b003",
      "name" : "manison"
    }
  ]
}]

"name" : "cruz" coming first because alphabatically C comes fast than J AND M (which is in second json)

And Prenelop and cruz didn't switched just the main document json switched as per the name order

Query i am using

db.traffic.aggregate([
  {$unwind: "$customFieldArray"}, 
  {$sort: {"customFieldArray.field_value":1}}, 
  {$group: {_id:"$_id", customFieldArray: {$push:"$customFieldArray"}}}
]);

But it is sorting inside like taking cruz to penelope and vice versa.

And main json staying stable.

Please have a look

Upvotes: 1

Views: 45

Answers (1)

Ashh
Ashh

Reputation: 46491

You can do with simple find query with sort cursor

db.traffic.find({}).sort({ "myarray.name": -1 })

From the docs

With arrays, a less-than comparison or an ascending sort compares the smallest element of arrays, and a greater-than comparison or a descending sort compares the largest element of the arrays.

Upvotes: 1

Related Questions