mongodb替换子文档中所有具有特定值的实例 [英] mongodb replace all instances of certain value for subdocument

查看:95
本文介绍了mongodb替换子文档中所有具有特定值的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的收藏集(称为工人"):

My collection (called "workers"):

"_id" : "500"
"type" : "Manager",
"employees" : [{
"name" : "bob"
"id" : 101
},{
"name" : "phil"
"id" : 102
}]

目标:对于每种类型的_id:经理AND包含"id"为102的子文档:将102替换为202.

Goal: for every _id that is a type: Manager AND that contains a subdocument that has an "id" of 102: replace 102 with 202.

所需的最终结果:

"_id" : "500"
"type" : "Manager",
"employees" : [{
"name" : "bob"
"id" : 101
},{
"name" : "phil"
"id" : 202
}]

我尝试过:

db.workers.update({type:'Manager','employees.id':'102'},{$set:{'employees.id':'202'}},{multi:true})

然后我做了以下两件事来验证:

I then did the following two things to verify:

db.workers.find({type: "Manager", 'employees.id': 102}).count()

我得到9的结果.

我也尝试过验证:

db.workers.find({$and: [{type: "Manager"},{"employees.id":60}]}).count()

这返回0.

我现在很困惑.我的更新有误吗?我发现错了吗?两者都是吗? "9"结果是否错误? "0"是错误的吗?

I am pretty confused at this point. Is my update wrong? is my find wrong? Is it both? Is the '9' result wrong? Is the '0' wrong?

推荐答案

您需要使用 $位置更新运算符可更新与您的查询匹配的特定元素.您的更新还使用了'102''202'的值,当这些字段为数字时,它们会尝试更新并匹配字符串.

You need to use the $ positional update operator to update the specific element that matched your query. Your update is also using values of '102' and '202' which makes the update try and match strings when those fields are numbers.

您的更新应如下所示:

db.workers.update(
    {type: 'Manager', 'employees.id': 102}, 
    {$set: {'employees.$.id': 202}}, 
    {multi: true})

这篇关于mongodb替换子文档中所有具有特定值的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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