如何从对象中取消设置对象

时间:2019-05-02 11:24:20

标签: javascript mongodb mongodb-query

这是我的文档:

{
    "_id" : ObjectId("5ccaa152feee5f2e60dff06f"),
    "name" : "ABC",
    "hobbies" : {
        "cricket" : {
            "hobbyName" : "cricket"
        },
        "football" : {
            "hobbyName" : "football"
        }
    }
},
{
    "_id" : ObjectId("5ccaa196feee5f2e60dff070"),
    "name" : "D",
    "hobbies" : {
        "Tennis" : {
            "hobbyName" : "Tennis"
        },
        "Volleyball" : {
            "hobbyName" : "Volleyball"
        },
        "basketball" : {
            "hobbyName" : "basketball"
        }
    }
}

var find = [ "Tennis", "football"];

假设我的hobbies对象下的文档存在网球和足球价值,我想取消设置该特定对象

我的代码:

var find = [ "Tennis", "football"];
db.Hobbies.find({})
.forEach(function(doc){
    var _id = doc._id;
    for(let i=0;i<find.length;i++){ 
    let remove  = find[i];
    let concate = "hobbies." + remove;
    let text = '"'+concate+'"';
        db.Hobbies.update(
            {'_id': _id},
            {$unset: { text : {_id: remove} }} 
        )
    }
})

我的预期输出是:

 {
    "_id" : ObjectId("5ccaa152feee5f2e60dff06f"),
    "name" : "ABC",
    "hobbies" : {
        "cricket" : {
            "hobbyName" : "cricket"
        }
    }
},
{
    "_id" : ObjectId("5ccaa196feee5f2e60dff070"),
    "name" : "D",
    "hobbies" : {
        "Volleyball" : {
            "hobbyName" : "Volleyball"
        },
        "basketball" : {
            "hobbyName" : "basketball"
        }
    }
}

2 个答案:

答案 0 :(得分:1)

阅读一些关于$unset运算符的信息。 基本上,您需要指定要取消设置的字段名称。 正确的代码段应如下所示:

db.Hobbies.update(
    {'_id': _id},
    {$unset: { "hobbies.Tennis": "", "hobbies.footbal": ""}, 
)

如果您想删除所有网球和足球爱好,也可以:

db.Hobbies.update(
    {},
    {$unset: { "hobbies.Tennis": "", "hobbies.footbal": ""}, 
    {multi: true}
)

编辑:动态方式。

let find = [ "Tennis", "football"];
db.Hobbies.find({})
    .forEach(function(doc){
       var _id = doc._id;
       let unset_obj = {};
       for(let i=0; i < find.length; i++){ 
            let key = `hobbies.${find[i]}`;
            unset_obj[key] = "";
        }
        db.Hobbies.update(
            {'_id': _id},
            {$unset: unset_obj} 
        )
    }
})

所有文件的动态方式:

let find = [ "Tennis", "football"];
var _id = doc._id;
let unset_obj = {};
for(let i=0; i < find.length; i++){ 
    let key = `hobbies.${find[i]}`;
    unset_obj[key] = "";
}
db.Hobbies.update(
            {},
            {$unset: unset_obj},
            {multi: true}
        )
    }
})

答案 1 :(得分:0)

请勿在db.Hobbies.find({})上循环。直接尝试:

    var find = [ "Tennis", "football"];
    for(let i=0;i<find.length;i++){ 
    let remove  = find[i];
    let concate = "hobbies." + remove;
    console.log(concate)
        db.Hobbies.update({},{$unset:{concate : 1}},{multi : true} 
        )
    }

这将取消所有文档的设置,还将跳过循环并进行查询