Sort subfields with unknown parent

我是研究僧i 提交于 2019-12-08 03:56:14

问题


I have a schema like this:

{
    "_id" : "555",
    "connections" : [ 
        {
            "id" : 111  
            "time" : 1456439249
        }, 
        {
            "id" : 222  
            "time" : 1556412345
        }
        ...
    }
    "users" : [ 
        "111" : {
            "id" : 111  
            "name" : "Michael"
        }, 
        "222" : {
            "id" : 222  
            "name" : "Jim"
        }
        ...
}

I want to get sorted connections by time and users data.

I'm trying with this:

db.getCollection('mycollecion')
    .find(
        {'_id' : '555'},
        {'_id' : 0, 'connections' : 1, 'users' : 1}
    ).sort({'connections.time' : 1})

Probably "connections.time" is not the correct path, because it's array.

How I can sort connections by the subfield "time"?

And it would be possible in the same query filter "users" by appearing on connections ids?


回答1:


Please try to do it through .aggregation()

> db.mycollecion.aggregate([
                            {$unwind: '$connections'}, 
                            {$sort: {'connections.time': 1}}, 
                            {$group: {
                                      _id: '$_id',
                                      connections: {$push: '$connections'}
                                     }
                            }]);


来源:https://stackoverflow.com/questions/35635755/sort-subfields-with-unknown-parent

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