MongoDB:按日期对具有相似结构的父项和子项进行排序



我有一个帖子的集合。每个帖子都有一些关于帖子本身的信息以及一系列评论。帖子和评论具有类似的结构。我的问题是:如何将有关帖子和评论的信息获取到同一级别并按日期对其进行排序?或者真的任何订单 - 我所需要的只是按日期排序的帖子和评论的平面列表。谢谢!

{
"comments": {
    "0": {
        "date": ISODate("2013-12-24T05:49:27.376Z"),
        "info": {
            "message"▼: "mlknlkjnjlnlkj",
            "date": ISODate("2013-12-24T05:49:27.376Z")
        },
        "type": "comment"
    },
    "1": {
        "date": ISODate("2013-12-25T08:32:47.859Z"),
        "info": {
            "message": "asdddd",
            "date": ISODate("2013-12-25T08:32:47.858Z")
        },
        "type": "comment"
    }
},
"date": ISODate("2013-12-24T04:57:13.741Z"),
"info": {
    "message": "12312312312",
    "date": ISODate("2013-12-24T04:57:13.0Z")
},
"type": "post"

}

编辑:事实证明,Rockmongo正在以这种地图外观的方式返回评论。但实际上注释在数组中而不是地图中。

尝试使用 mapReduce。

map = function () {
    emit(this._id, {
        type: this.type,
        date: this.date,
        info: this.info
    });
    for (var i in this.comments) {
        emit(this.comments[i]._id, {
            type: this.comments[i].type,
            date: this.comments[i].date,
            info: this.comments[i].info
        });
    }
}

db.your_collection.mapReduce(map, function () {}, {out: "posts_and_comments"})db.posts_and_comments.find().sort({"value.date": -1}).pretty()

最新更新