mongodb 分组时选择不相等的值

tnkciper  于 2023-04-20  发布在  Go
关注(0)|答案(1)|浏览(120)

每个文档描述客户协议(决策,而非价值),简化:

{
    "_id": "123",
    "customerID" : "Smith"
    "agreement": [
        {"agreementType":"A"
        "agreementValue":"T"},
        {"agreementType":"B"
        "agreementValue":"T"}]
}
{
    "_id": "124",
    "customerID" : "Smith"
    "agreement": [
        {"agreementType":"A"
        "agreementValue":"F"},
        {"agreementType":"B"
        "agreementValue":"T"}]
}
{
    "_id": "125",
    "customerID" : "Brown"
    "agreement": [
        {"agreementType":"A"
        "agreementValue":"T"},
        {"agreementType":"B"
        "agreementValue":"T"}]
}
{
    "_id": "126",
    "customerID" : "Brown"
    "agreement": [
        {"agreementType":"A"
        "agreementValue":"T"},
        {"agreementType":"B"
        "agreementValue":"T"}]
}

我需要查询所有对同一agreementType具有不同agreementValues的客户(例如,单个客户同意,第二天不同意)。它应该返回Smith(agreementType=A的不同值)。
目前我可以找到所有的重复,但不能限制到那些不同的价值观

wz3gfoph

wz3gfoph1#

您可以$unwindagreement数组并执行$group以获得agreementValue的不同值。$match,其中$size大于1,以获得所需的记录。

db.collection.aggregate([
  {
    "$unwind": "$agreement"
  },
  {
    "$group": {
      "_id": {
        "customerID": "$customerID",
        "agreementType": "$agreement.agreementType"
      },
      "agreementValues": {
        "$addToSet": "$agreement.agreementValue"
      }
    }
  },
  {
    $match: {
      $expr: {
        $gt: [
          {
            $size: "$agreementValues"
          },
          1
        ]
      }
    }
  },
  {
    $group: {
      _id: "$_id.customerID"
    }
  }
])

Mongo Playground

相关问题