如何获取 mongo 中不同字段中具有价值的文档数

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

我有一些文件如下

  {
    _id: 1,
    lender_id: 10,
    borrower_id: 20,
    message: 'Message from lender'
  },
  {
    _id: 2,
    lender_id: 20,
    borrower_id: 10,
    message: 'Response to lender'
  }
  {
    _id: 3,
    lender_id: 10,
    borrower_id: 30,
    message: 'Message to other user'
  }

我想在 lender_id 字段或 borrower_id 等于 10 时获取此特定情况下的文档数。

我试试这个:

    chats = await Chat.aggregate([
        {
            $match: { $or: [
                {lender_id: 10},
                {borrower_id: 10}
            ]}
        },
        {
            $group: {
                _id: null,
                differentChats: {$sum: 1}
            }
        },
    ])

    // Response: [ { _id: null, differentChats: 3 } ] --- must be 2

如何获得唯一聊天的总数。 感谢阅读。

我们需要创建一个 Set 的唯一 lender_idborrower_id 如下所示(通过更改顺序)。在最后阶段,我们取 Set 大小。

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