search

Home  >  Q&A  >  body text

mongodb储存即时聊天的时候如何取出用户聊天列表

{
        "_id" : ObjectId("576cfd363325ffaa1dbdde15"),
        "current_uid" : "5",
        "to_uid" : "3",
        "content" : "你大爷"
    },
    {
        "_id" : ObjectId("576cfd6e3325ff501e07f4ae"),
        "current_uid" : "5",
        "to_uid" : "3",
        "content" : "郭德纲"
    },
    {
        "_id" : ObjectId("576cfe753325ff501ea76603"),
        "current_uid" : "5",
        "to_uid" : "4",
        "content" : "325235"
    }

存的时候如上所示,想要获取用户ID为5的这个跟哪些人聊过天,也就是3和4这2个用户,现在想要获取包括content的信息,也就是跟该用户最新的一条记录,比如3这个用户,我要获取的就是郭德纲这个content而不是上面那条,这个应该怎么查询,初学mongodb,球帮助

仅有的幸福仅有的幸福2765 days ago620

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-02 09:22:07

    This is a very typical groupingTOP Nproblem. There are also corresponding expressions in SQL databases, such as SQLServer

    ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)

    Using aggregation就可以解决了。aggregation in MongoDB is a big topic. It is impossible to explain all the content here. You can only check the documentation to understand the various operators used below.

    db.chat.aggregate([
        {$match: {current_uid: "5"}},
        {$sort: {_id: -1}},
        {$group: {_id: {current_uid: "$current_uid", to_uid: "$to_uid"}, content: {$first: "$content"}}}
    ])
    

    A few explanations:

    1. Use {$sort: {_id: -1}}其实就是时间倒序。_id which contains time, and sorting it can most of the time be considered as sorting time;

    2. $first取到了第一个元素。如果想取头n个元素怎么办?$push+$slice That’s it;

    3. How can the above query be made faster? db.chat.createIndex({current_uid: 1, _id: 1})

    reply
    0
  • Cancelreply