首頁 >後端開發 >php教程 >Mongodb 根据子文档的某个特定字段排序的问题

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

WBOY
WBOY原創
2016-06-06 20:28:531562瀏覽

<code>/* 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
}</code>

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

回复内容:

<code>/* 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
}</code>

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

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

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

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn