首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoose Group和Populate :获取一个人曾经与之交谈过的用户的唯一列表,比如whatsapp屏幕,在这里您有所有以前的用户。

Mongoose Group和Populate :获取一个人曾经与之交谈过的用户的唯一列表,比如whatsapp屏幕,在这里您有所有以前的用户。
EN

Stack Overflow用户
提问于 2021-09-15 19:28:36
回答 1查看 111关注 0票数 1

我一直在开发一个聊天应用程序,我需要显示与用户对话的用户列表。更像whatsapp的第一个屏幕,其中有所有发短信的用户的列表。

我的messagesSchema如下:

代码语言:javascript
复制
from : {type : mongoose.Types.ObjectId, ref : "Users"},
to : {type : mongoose.Types.ObjectId, ref : "Users"},
messageType : String,
messageContent :String,
images : [Object],
poster : Object,
status : String,
date: { type: Date, default: Date.now }

我正在使用nodejs,我尝试过很多农耕、group和其他猫鼬查询,但都失败了。

请帮助我查询,以获得所有不同的独特用户,一个人一直在与他们的最后一条消息交谈,并填充' to‘和’从‘。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-16 01:03:23

数据:

代码语言:javascript
复制
[
  {
    "_id": ObjectId("100000000000000000000000"),
    "from": ObjectId("100000000000000000000000"),
    "to": ObjectId("200000000000000000000000"),
    "date": ISODate("2021-09-03T11:23:25.184Z"),
    "messageContent": "111"
  },
  {
    "_id": ObjectId("200000000000000000000000"),
    "from": ObjectId("200000000000000000000000"),
    "to": ObjectId("100000000000000000000000"),
    "date": ISODate("2021-09-02T11:23:25.184Z"),
    "messageContent": "222"
  },
  {
    "_id": ObjectId("300000000000000000000000"),
    "from": ObjectId("300000000000000000000000"),
    "to": ObjectId("100000000000000000000000"),
    "date": ISODate("2021-09-04T11:23:25.184Z"),
    "messageContent": "333"
  },
  {
    "_id": ObjectId("400000000000000000000000"),
    "from": ObjectId("300000000000000000000000"),
    "to": ObjectId("400000000000000000000000"),
    "date": ISODate("2021-09-05T11:23:25.184Z"),
    "messageContent": "444"
  }
]

聚合:(您是ObjectId("100000000000000000000000"))

代码语言:javascript
复制
db.collection.aggregate([
  {
    $match: {
      "$or": [
        { "from": ObjectId("100000000000000000000000") },
        { "to": ObjectId("100000000000000000000000") }
      ]
    }
  },
  {
    $project: {
      whom: {
        $first: {
          $filter: {
            input: [ "$from", "$to" ],
            as: "i",
            cond: { $ne: [ "$$i", ObjectId("100000000000000000000000") ]
            }
          }
        }
      },
      date: 1,
      messageContent: 1,
      to: 1,
      from: 1
    }
  },
  {
    $sort: { "date": -1 }
  },
  {
    $group: {
      _id: "$whom",
      date: { "$first": "$date" },
      message: { "$first": "$messageContent" },
      to: { "$first": "$to" },
      from: { "$first": "$from" }
    }
  }
])

结果:

代码语言:javascript
复制
[
  {
    "_id": ObjectId("300000000000000000000000"),
    "date": ISODate("2021-09-04T11:23:25.184Z"),
    "message": "333"
  },
  {
    "_id": ObjectId("200000000000000000000000"),
    "date": ISODate("2021-09-03T11:23:25.184Z"),
    "message": "222"
  }
]

示例: 蒙古操场

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69198813

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档