MongoDB query with same data referance

Hello,When I find a data in my model, I want to compare two variables in this data, but one of them is the data of the object. How can I achieve this?

exports.getConversation = catchAsync(async (req, res, next) => {
    const loginUser = req.user.id;
    const conversationId = req.params.id;
    const conversation = await Conversation.find({
            "deleteMessagesBy.deleterID": loginUser,
            $updateAt: {
                $dsadsa: "deleteMessagesBy.$.deleteAt"
            },
            _id: conversationId,
        }, "id conversationParticipant conversationType readBy lastMessage updateAt deleteMessagesBy"
        //readBy
    ).populate({
        path: "conversationParticipant",
        select: "name username profileImage ",
    }).populate({
        path: "lastMessage",
        select: "messageData type sentAt category  conversationId sender",
    });
    res.status(200).json({
        status: "success",
        conversation: conversation,
    });
});

Data;
dsadadsa

Hello :wave: @Mehmet_Kasap,

Welcome to the MongoDB Community!

In Mongoose you can try using $unwind - Mongoose:

var unwind = {$unwind: '$deleteMessageBy'};

var match = {$match: {'deleteMessageBy.deleterID': req.user.id}};

Conversation.aggregate(match, unwind, function(err, result) {
    console.log(result);
});

Note that this is an untested example and may not work in all cases. Please do test any code thoroughly with your use case so that there’s no surprises.

Now you have the result and you can perform further operations.

Alternatively, You can compare the data of the object by using MongoDB aggregations - by first unwinding the array of objects by using $unwind, and can use $let operator to compare the dates.

Something like this:

db.collection.aggregate([
  {
    "$unwind": "$deleteMessageBy",
  },
  {
    $project: {
      compareDate: {
        $let: {
          vars: {
            deleteTime: "$deleteMessageBy.deleteAt",
            updateTime: "$updatedAt"
          },
          in: {
            $lt: [ "$$deleteTime", "$$updateTime" ]
          }
        }
      }
    }
  }
])

If you have any doubts, please feel free to reach out to us.

Regards,
Kushagra Kesav

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.