$Push 如果对象不存在

Sno*_*opy 5 mongodb aggregation-framework

我的students文档中有一系列,VirtualClass我的目标是创建一个没有重复学生的名册。

我想将VirtualClass与老师和$push学生匹配到一个数组中。

虚拟类模式

const VirtualClassSchema = new Schema({
  name: { type: String, required: true },
  descriptionHeading: { type: String, required: true },
  room: { type: String },
  teacher: {
    userId: { type: Schema.Types.ObjectId, ref: "User" },
    name: { type: String },
    profile_picture: { type: String }
  },
  students: [
    {
      userId: { type: Schema.Types.ObjectId, ref: "User" },
      name: { type: String },
      profile_picture: { type: String }
    }
  ],
...
Run Code Online (Sandbox Code Playgroud)

我目前的查询如下

      VirtualClass.aggregate([
        { $match: { "teacher.userId": user._id } },
        {
          $group: {
            _id: null,
            students: { $addToSet: "$students" }
          }
        }
      ])
Run Code Online (Sandbox Code Playgroud)

返回:

[
    {
        "_id": null,
        "students": [
            [
                {
                    "_id": "5e84d1a1ab3ebf54283b8cb2",
                    "userId": "5dd27452592f600900235945",
                    "name": "student  zero",
                    "profile_picture": "https://productionstemulistorage.blob.core.windows.net/stemuli/profile-picture-6e609f3b-44cb-44c0-888a-1b6767e3072d"
                }
            ],
            [
                {
                    "_id": "5e84d1a1ab3ebf54283b8cb4",
                    "userId": "5dd27452592f600900235945",
                    "name": "student  zero",
                    "profile_picture": "https://productionstemulistorage.blob.core.windows.net/stemuli/profile-picture-6e609f3b-44cb-44c0-888a-1b6767e3072d"
                }
            ]
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

预期成绩:

_id: null,
"students":
[
     {
       "_id": "5e84d1a1ab3ebf54283b8cb4",
        "userId": "5dd27452592f600900235945",
        "name": "student  zero",
        "profile_picture": "https://productionstemulistorage.blob.core.windows.net/stemuli/profile-picture-6e609f3b-44cb-44c0-888a-1b6767e3072d"
    }
]

Run Code Online (Sandbox Code Playgroud)

谢谢!

Naf*_*Joy 2

您需要$unwind然后在聚合函数中$project删除_idbefore 。$group

代码:

[
  {
    "$match": {
      "teacher.userId": 1
    }
  },
    {
    "$unwind": "$students"
  },
    {
    "$project": {
      "students._id": 0
    }
  },
  {
    "$group": {
      "_id": null,
      "students": {
        "$addToSet": "$students"
      }
    }
  }

]
Run Code Online (Sandbox Code Playgroud)

示例代码和管道说明