mongoDB-使用$set和一个对象更新文档

mongoDB - update document using $set and a object

本文关键字:一个对象 更新 文档 set 使用 mongoDB-      更新时间:2023-09-26

我有一个对象,它包含来自输入字段的多个值。现在我想更新一个特定的集合。我是这样做的:

var info = {age: t.find('input[name=age]').value, organization: t.find('input[name=organization]').value};
Users.update({_id: userId}, {$set: {profile: info}});

现在的问题是,这会删除更新操作之前存在的profile值。是否可以在文档中保留不属于info对象的值?

如有任何帮助,我们将不胜感激。

您可以在$set键中使用点表示法来更新嵌入对象中的各个字段:

var set = {
    'profile.info.age': t.find('input[name=age]').value,
    'profile.info.organization': t.find('input[name=organization]').value
};
Users.update({_id: userId}, {$set: set});