-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'
        }
    ]
}

Get last chat of chatid 'userid1_userid2' only if field 'deleted_by_userid1' not exist

Deepak
  • 145
  • 2
  • 9

1 Answers1

1

You can do the following with aggregation,by unwinding the "chats" array field and sorting the documents which do not have the "deleted_by_userid1" field,

db.collection.aggregate([
{"$unwind":"$chats"},
{"$match":{"chats.deleted_by_userid1":{$exists:false}}},
{"$sort":{"chats.time":-1}},
{"$limit":1}
])
fractal397
  • 534
  • 1
  • 5
  • 11