MongoDB
 sql >> Datenbank >  >> NoSQL >> MongoDB

So erhalten Sie die letzte Nachricht aus der Chat-Konversation in Mongodb

Das Problem ist, wie Nachrichten stored werden .

Gespeicherte Daten:

fromUser 123 and toUser 456
fromUser 456 and toUser 123

Wenn Sie es also gruppieren, sind sie logischerweise gleich , aber not for grouping .

Lösung:

Wir müssen sicherstellen, dass Sender / Empfänger immer auf dem gleichen Weg ankommen

1. Create array where we store sender / receiver
2. Order that array `[123, 456] [456, 123] => [123,456], [123,456]`
3. Group by this ordered array (In Mongo way: $project, $unwind, $sort, $group - push)
db.chats.aggregate([
  {
    $match: {
      $or: [
        {
          "toUser": 123
        },
        {
          "fromUser": 123
        }
      ]
    }
  },
  {
    "$project": {
      toUser: 1,
      fromUser: 1,
      message: 1,
      timeStamp: 1,
      fromToUser: [
        "$fromUser",
        "$toUser"
      ]
    }
  },
  {
    $unwind: "$fromToUser"
  },
  {
    $sort: {
      "fromToUser": 1
    }
  },
  {
    $group: {
      _id: "$_id",
      "fromToUser": {
        $push: "$fromToUser"
      },
      "fromUser": {
        "$first": "$fromUser"
      },
      "toUser": {
        "$first": "$toUser"
      },
      "message": {
        "$first": "$message"
      },
      "timeStamp": {
        "$first": "$timeStamp"
      }
    }
  },
  {
    "$sort": {
      "timeStamp": -1
    }
  },
  {
    "$group": {
      "_id": "$fromToUser",
      "fromUser": {
        "$first": "$fromUser"
      },
      "toUser": {
        "$first": "$toUser"
      },
      "message": {
        "$first": "$message"
      },
      "timeStamp": {
        "$first": "$timeStamp"
      }
    }
  }
])

Ergebnis

[
  {
    "_id": [
      101,
      123
    ],
    "fromUser": 123,
    "message": "Kk",
    "timeStamp": "2019-10-09 18:31:12:1212 PM +05:30",
    "toUser": 101
  },
  {
    "_id": [
      123,
      456
    ],
    "fromUser": 123,
    "message": "2",
    "timeStamp": "2019-10-09 18:31:21:2121 PM +05:30",
    "toUser": 456
  }
]

MongoPlayground