如何在mongodb中使用facet操作查找字段的不同值

问题描述

filteredAccording 部分和categorizedBy 使用我在链接中提供的查询按预期工作,但我在finddistinct 部分遇到了问题。

在mongodb中我有以下数据:

 {
        "_id": 10001,"university": "SPYU","Courses": [
          "English","french"
        ],"dept": [
          "Literature"
        ],"type": [
          "Autonomous"
        ],"status": "ACTIVE","isMarked": true
      },{
        "_id": 10002,"status": "NON-ACTIVE","isMarked": true
      }

我希望得到的回应是:

 "university": [
  {
    "name": "Literature","values": [
      {
        "_id": 10001,"isMarked": true
      }
    ]
  }
],"finddistinct": [
    {​​​​​​​​
      "name": "Courses","values": [
        "English","french"
      ]
    }​​​​​​​​,{​​​​​​​​
      "name": "Status","values": [
        "ACTIVE","NON-ACTIVE"
      ]
    }​​​​​​​​
  ]

我使用此链接进行了尝试,但没有按预期响应。 https://mongoplayground.net/p/XECZvRMmt3T

现在,响应是这样的

 "universities": [
  {
    "name": "Literature","finddistinct": [
    {​​​​​​​​
      "Courses": [
        "English",{​​​​​​​​
      "status": [
        "ACTIVE","NON-ACTIVE"
      ]
    }​​​​​​​​
  ]

任何帮助将不胜感激!

解决方法

快速修复您的查询,

大学:

  • $addFields,删除 $project 并只为 isMarked 添加一个操作
  • $unwind 解构 dept 数组
  • $group by dept 并获取根值数组

findDistinct:

  • $group by null 并获得唯一的 courses 数组和 status
  • $reduce 迭代 Courses 嵌套数组的循环并使用 $setUnion
  • 获取唯一数组
  • status 字段中创建数组和 dest
  • $unwind 解构 dest 数组
  • $replaceRootdest 对象替换为 root
db.collection.aggregate([
  { $match: { university: "SPYU" }
  },{
    $facet: {
      universities: [
        { $addFields: { isMarked: { $in: ["French","$Courses"] } } },{ $unwind: "$dept" },{
          $group: {
            _id: "$dept",values: { $push: "$$ROOT" }
          }
        }
      ],findDistinct: [
        {
          $group: {
            _id: null,Courses: { $addToSet: "$Courses" },Status: { $addToSet: "$status" }
          }
        },{
          $project: {
            _id: 0,dist: [
              {
                name: "Courses",values: {
                  $reduce: {
                    input: "$Courses",initialValue: [],in: { $setUnion: ["$$this","$$value"] }
                  }
                }
              },{
                name: "Status",values: "$Status"
              }
            ]
          }
        },{ $unwind: "$dist" },{ $replaceRoot: { newRoot: "$dist" } }
      ]
    }
  }
])

Playground