将文档插入满足两个条件的文档

时间:2019-06-03 11:20:05

标签: java mongodb spring-boot

我想在已经存在的文档中插入一个文档(数组)。

我已经遍历了有关将文档插入文档中的堆栈溢出的主题。我已经读过$push并了解了,但是我的要求没有什么不同。因此,我想做的是-我想为符合特定项目的特定员工添加目标。

{
    "empCode": "001",
    "emapName": "ABC",
    "projects": [{
        "projectName": "P001",
        "projectMoreDetails": "projectMoreDetails",
        "Goals": [{
            "GoalName": "Goal1",
            "GoalMoreDetails": "GoalMoreDetails"
        }, {
            "GoalName": "Goal2",
            "GoalMoreDetails": "GoalMoreDetails"
        }]
    }, {
        "projectName": "P002",
        "projectMoreDetails": "projectMoreDetails",
        "Goals": [{
            "GoalName": "Goal1",
            "GoalMoreDetails": "GoalMoreDetails"
        }, {
            "GoalName": "Goal2",
            "GoalMoreDetails": "GoalMoreDetails"
        }]
    }]

}

有人可以告诉我如何为员工代码“ 001”添加项目“ P002”的更多目标吗?

1 个答案:

答案 0 :(得分:0)

要找到匹配的文档,请使用:

{empCode:"001", projects:{$elemMatch:{"projectName":"P002"}}}

在更新时,您可以使用$来获取匹配的数组元素。

您的最终更新查询将类似于:

db.emp.update(
    {empCode:"001", projects:{$elemMatch:{"projectName":"P002"}}},
    {$push:{"projects.$.Goals":{GoalName:"Upvote"}}}
)