mongodb只更新特定的子元素

时间:2013-07-17 10:52:49

标签: javascript node.js mongodb express

我的数据库结构如下:

{
  "_id" : ObjectId("51e66873f6a6600436000001")
  ,"email" : "asd@asd.de",
  ,"attribute_group_a" : {
     "attribute_a" : ""
     ,"attribute_b" : ""
     ,"attribute_c" : ""
     ,"attribute_d" : ""
  },
  ,"attribute_group_b" : {
      "attribute_subgroup_b_a" : {
           "attribute_a" : ""
           ,"attribute_b" : ""
           ,"attribute_c" : ""
           ,"attribute_d" : ""
       }
       ,"attribute_subgroup_b_b" : { 
           "attribute_a" : ""
           ,"attribute_b" : ""
           ,"attribute_c" : ""
           ,"attribute_d" : ""
       }
  }
}

所以我想说要更新att_subgrp_b_a:

exports.updateProfil = function(req, res, item, callback) {
    var email = req.session.email;
    db.collection('profiles', function(err, collection) {
        collection.update({"email": email},{$set: item}, function(err, result)

var“item”看起来像:

{
    attribute_group_b:
    {
        attribute_subgroupgroup_b_a: 
        {
            att_a: "xy"
            ,att_b: "xy"
        }
    }
}

当我现在更新文件=>它会删除attr_group_b中的所有内容并将其替换为“item”

这意味着attr_subgrp_b_b完全消失,所有其他属性(attr_subgrp_b_a)都没有更新




我希望它在“item”中查找属性,将它们替换为db,让所有其他obj不受影响

1 个答案:

答案 0 :(得分:1)

尝试以下查询

  var email='emailid';
  var item='whichuwanttoupdate';
  collection.update(
             {"email": email},
             {$set:{'attribute_group_b.attribute_subgroup_b_a':item}},
             function(err,result){

     });