当前位置:Gxlcms > PHP教程 > Mongodb根据子文档的某个特定字段排序的问题

Mongodb根据子文档的某个特定字段排序的问题

时间:2021-07-01 10:21:17 帮助过:8人阅读

/* 1 */
{
    "_id" : ObjectId("55e542cd7f8b9aca2b8b4568"),
    "game_id" : 1103,
    "tags" : [ 
        {
            "tag_id" : 10,
            "name" : "西游",
            "rank" : 10,
        }, 
        {
            "tag_id" : 123,
            "name" : "网游",
            "rank" : 1,
        }, 
    ],
    "time_sort" : 1435306
}

/* 2 */
{
    "_id" : ObjectId("55dd8fe67f8b9a25528b64f7"),
    "game_id" : 6408,
    "tags" : [ 
        {
            "tag_id" : 28,
            "name" : "白领最爱",
            "rank" : 20,
        }, 
        {
            "tag_id" : 123,
            "name" : "网游",
            "rank" : 2,
        }, 
    ],
    "time_sort" : 1411574
}

/* 3 */
{
    "_id" : ObjectId("55dd91197f8b9a25528b9585"),
    "game_id" : 18498,
    "tags" : [ 
        {
            "tag_id" : 19,
            "name" : "回合制",
            "pc_rank" : 120,
        }, 
        {
            "tag_id" : 123,
            "name" : "网游",
            "rank" : 3,
        }, 
    ],
    "time_sort" : 1437385
}

现在只想通过 网游标签的rank排序,语句应该怎么写

回复内容:

/* 1 */
{
    "_id" : ObjectId("55e542cd7f8b9aca2b8b4568"),
    "game_id" : 1103,
    "tags" : [ 
        {
            "tag_id" : 10,
            "name" : "西游",
            "rank" : 10,
        }, 
        {
            "tag_id" : 123,
            "name" : "网游",
            "rank" : 1,
        }, 
    ],
    "time_sort" : 1435306
}

/* 2 */
{
    "_id" : ObjectId("55dd8fe67f8b9a25528b64f7"),
    "game_id" : 6408,
    "tags" : [ 
        {
            "tag_id" : 28,
            "name" : "白领最爱",
            "rank" : 20,
        }, 
        {
            "tag_id" : 123,
            "name" : "网游",
            "rank" : 2,
        }, 
    ],
    "time_sort" : 1411574
}

/* 3 */
{
    "_id" : ObjectId("55dd91197f8b9a25528b9585"),
    "game_id" : 18498,
    "tags" : [ 
        {
            "tag_id" : 19,
            "name" : "回合制",
            "pc_rank" : 120,
        }, 
        {
            "tag_id" : 123,
            "name" : "网游",
            "rank" : 3,
        }, 
    ],
    "time_sort" : 1437385
}

现在只想通过 网游标签的rank排序,语句应该怎么写

管道查询然后用unwind打撒tags,再排序

"tags" : [ 
        {
            "tag_id" : 28,
            "name" : "白领最爱",
            "rank" : 20,
        }, 
        {
            "tag_id" : 123,
            "name" : "网游",
            "rank" : 2,
        }, 
    ],

tags数组里面的两个元素都有rank字段,你要根据第一个rank排序还是第二个rank排序?

人气教程排行