0

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})
2
  • sorry it's db.myarray.find().sort( { order: 1 } ) Commented Mar 16, 2015 at 12:05
  • The Aggregation Framework works well for such queries, why don't you try db.collection.aggregate({ $unwind: '$myarray' }, { $sort: {'myarray.order': -1 }})? Commented Mar 16, 2015 at 12:11

2 Answers 2

3

You can use aggregation pipelines

db.collection.aggregate([
    { "$unwind": "$myarray" }, 
    { "$sort": { "myarray.order": 1 }}, 
    { "$group": { "_id": "$_id", "myarray": { "$push": "$myarray" }}}
])
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

it is ok but i need to get document with _id 1 and sort it's array data
@user298582 That is not a problem, see the edited information. The real issue as I see it is making the decision to either keep the arrays sorted or do it on request. Unless you change the sorting pattern all the time the former makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.