如何在MongoDb中使用更新聚合

szqfcxe2  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(145)

我示例数据库:

"Employee": [ { "empeId": "e001",
             "fName": "James",
             "lName": "Bond",
             "email": "jamesbond@hotmail.com",
             "experience": [
                    "Database Design",
                    "SQL",
                    "Java" ]
                },
                { "empeId": "e002",
              "fName": "Harry",
              "lName": "Potter",
              "experience": [
                    "Data Warehouse",
                    "SQL",
                    "Spark Scala",
                    "Java Scripts" ]
                } ],
  "Project": [ { "projectId": "p001",
            "projectTitle": "Install MongoDB" },
                {   "projectId": "p002",
            "projectTitle": "Install Oracle" },
                {   "projectId": "p003",
            "projectTitle": "Install Hadoop" } ],
  "EmployeeProject": [ {  "empeId": "e001",
                   "projectId": "p001",
                   "hoursWorked": 4 },
                     { "empeId": "e001",
                   "projectId": "p003",
                   "hoursWorked": 2 },
                     { "empeId": "e002",
                   "projectId": "p003",
                   "hoursWorked": 5 } ]

我想使用empeId为的用户的“test”更新阵列体验:e001号
所需输出:

"Employee": [ { "empeId": "e001",
             "fName": "James",
             "lName": "Bond",
             "email": "jamesbond@hotmail.com",
             "experience": [
                    "Database Design",
                    "SQL",
                    "Java",
                    "test"
]
                }]

我试过用

db.emp.updateOne([
   {$unwind: "$Employee"},
   {$match: {"Employee.emepId" : "e001" }}
], 
{$push: {"Employee.experience" : "test"}})

并且出现语法错误:无效的属性ID @(shell):1:31
这就是使用管道聚合进行更新的语法的工作方式吗?

pgvzfuti

pgvzfuti1#

最简单和干净的方法(使用arrayFilters):

db.collection.update({ Employee.empeId" : "e001"},
{
  "$push": {
   "Employee.$[x].experience": "test"
  }
 },
 {
  arrayFilters: [
  {
   "x.empeId": "e001"
  }
 ]
})

Playground1
通过更新/聚合:

db.collection.update({ Employee.empeId" : "e001" },
 [
 {
  $set: {
  "Employee": {
    $map: {
      input: "$Employee",
      as: "m",
      in: {
        $cond: [
          {
            $eq: [
              "$$m.empeId",
              "e001"
            ]
          },
          {
            $mergeObjects: [
              "$$m",
              {
                experience: {
                  $concatArrays: [
                    "$$m.experience",
                    [
                      "test"
                    ]
                  ]
                }
              }
            ]
          },
          "$$m"
        ]
      }
    }
    }
   }
  }
 ])

Playground2

相关问题