欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-03-28 21:08:14
...
/* 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排序?

相关标签: php mongodb