Mongo DB 更新到子数组文档 [英] Mongo DB Update to a sub array document

查看:27
本文介绍了Mongo DB 更新到子数组文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构

{
        "_id" : ObjectId("562dfb4c595028c9r74fda67"),
        "office_id" : "123456",
        "employee" : [
                {
                        "status" : "declined",
                        "personId" : "123456",
                        "updated" : NumberLong("1428407042401")
                }
        ]
}

这个办公室可以有多个人.如果我想更新该特定 office_id 下所有人员的员工状态以说已批准",有没有办法.我正在通过普通的 mongo java 驱动程序尝试相同的操作.我是什么尝试是使用查询生成器获取所有 office id,然后遍历列表并保存文档.有些我对我遵循的迭代方法(获取、迭代和保存)不满意.请建议是否有替代方法.

This office can have multiple persons.Is there a way if I want to update the employee status for all the person under that specific office_id to say "approved".I am trying the same through plain mongo java driver.What I am trying is get all the office id using a query builder , then iterate over the list and save the document.Somewhat I am not satisfied with the iterative approach(fetch,iterate and save ) that I am following.Please suggest if there is alternative way.

推荐答案

您可以使用 $ 位置运算符:

You can update using the $ positional operator:

db.collection.update(
    {
        "office_id" : "123456", 
        "employee.status": "declined"
    }, 
    {
        "$set": { "employee.$.status": "approved" }
    }
);

位置运算符从与查询匹配的数组中保存元素的索引(在上述情况下为 0).这意味着如果您事先知道元素的位置(这在现实生活中几乎不可能),您只需将更新语句更改为: {"$set": {"employee.0.status":批准"}}.

The positional operator saves the index (0 in the case above) of the element from the array that matched the query. This means that if you knew the position of the element beforehand (which is nearly impossible in a real life case), you could just change the update statement to: {"$set": {"employee.0.status": "approved"}}.

请注意,$ 位置运算符(目前)仅更新第一个相关文档,有一个 JIRA 票证.

Please note that the $ positional operator (for now) updates the first relevant document ONLY, there is a JIRA ticket for this.

编辑:

使用Java驱动,上面的更新可以这样完成(未经测试):

Using the Java driver, the above update may be done like so (untested):

BasicDBObject update = new BasicDBObject();
BasicDBObject query = new BasicDBObject();
query.put("office_id", "123456");
query.put("employee.status", "declined");

BasicDBObject set = new BasicDBObject("$set", update);
update.put(""employee.$.status", "approved");

collection.update(query, set);

这篇关于Mongo DB 更新到子数组文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆