Ali Kianinejad
Ali Kianinejad

Reputation: 963

Get And Sort In Array Mongodb

I have document like this

{
    "id": "1",
    "myarray": [
        {
            "_id": "4",
            "name": "d",
            "order": 4
        },
        {
            "_id": "1",
            "name": "a",
            "order": 1
        },
        {
            "_id": "2",
            "name": "b",
            "order": 2
        }
    ]
}

i want to see sort data in array by order when get from db i am trying some query like below but it seems not OK and nothing changed

 db.collection.aggregate([{$unwind: "$myarray"},{$project: {orders:"$myarray.order"}},{$group: {_id:"$_id",min:{$min: "$orders"}}},{$sort: {min:1}}])

db.myarray.find({},{$sort:{"myarray.order":-1}})
db.collection.find({"_id":"1"}).sort({"myarray.order":1})

what is correct query?

I need something like this

db.collection.find({"_id":"1"}).sort({"myarray.order":1})

Upvotes: 0

Views: 149

Answers (2)

Neil Lunn
Neil Lunn

Reputation: 151072

To sort in a response and not permanently:

db.collection.aggregate([
    { "$match": { "_id": 1 } },
    { "$unwind": "$myarray" },
    { "$sort": { "myarray.order": 1 } },
    { "$group": {
        "_id": "$_id",
        "myarray": { "$push": "$myarray" }
    }}
])

To alter permanently:

db.collection.update(
    { "_id": 1 }, 
    { "$push": { "myarray": { "$each": [], "sort": { "order": 1 } } }},
    { "multi": true }
)

If this is what you generally want then your best option is generally to $sort the array as you $push a new element or elements via $each as another modifier.

Of course if you $pull elements from the array the "current" syntax requires another query to be issued in order to sort the array just as is already shown.

It's generally better to keep your results in the order you expect, rather than order them in post processing, as the latter will always come at a cost that is greater than the former approach.

Upvotes: 1

Sede
Sede

Reputation: 61225

You can use aggregation pipelines

db.collection.aggregate([
    { "$unwind": "$myarray" }, 
    { "$sort": { "myarray.order": 1 }}, 
    { "$group": { "_id": "$_id", "myarray": { "$push": "$myarray" }}}
])

Upvotes: 3

Related Questions