-1
let docs = {
    chatid: 'userid1_userid2',
    chats: [
        {
            from: 'user1',
            to: 'user2',
            message: 'Hii',
            time: '2021-06-26T16:14:08.477+00:00'
        },
        {
            from: 'user1',
            to: 'user2',
            message: 'Listen',
            time: '2021-06-26T16:14:09.477+00:00',
            deleted_by_userid1: '2021-06-26T16:14:10.477+00:00'
        }
    ]
}

仅当字段 'deleted_by_userid1' 不存在时获取聊天 ID 'userid1_userid2' 的最后一次聊天

4

1 回答 1

1

您可以通过聚合执行以下操作,通过展开“chats”数组字段并对没有“deleted_by_userid1”字段的文档进行排序,

db.collection.aggregate([
{"$unwind":"$chats"},
{"$match":{"chats.deleted_by_userid1":{$exists:false}}},
{"$sort":{"chats.time":-1}},
{"$limit":1}
])
于 2021-06-28T18:07:32.573 回答