how to get the count of documents with value in different fields in mongo how to get the count of documents with value in different fields in mongo mongoose mongoose

how to get the count of documents with value in different fields in mongo


We need create a Set of unique lender_id and borrower_id like shown below (by changing the order). In the last stage, we take the Set size.

chats = await Chat.aggregate([  {    $match: {      $or: [ {lender_id: 10}, {borrower_id: 10} ]    }  },  {    $group: {      _id: null,      differentChats: {        $addToSet: {          $cond: [            { $gt: ["$lender_id", "$borrower_id"]},            [ "$lender_id", "$borrower_id" ],            [ "$borrower_id", "$lender_id" ]          ]        }      }    }  },  {    $project: {      differentChats: { $size: "$differentChats" }    }  }])

MongoPlayground