Get And Sort In Array Mongodb

耗尽温柔 提交于 2019-12-12 06:07:08

问题


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})

回答1:


You can use aggregation pipelines

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



回答2:


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.



来源:https://stackoverflow.com/questions/29076213/get-and-sort-in-array-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!