node.jsmongodbexpressmongodb-querymongodb-nodejs-driver

Mongodb Query Only if Exist


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


Solution

  • 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}
    ])