如何在不使用循环或扫描数据库的情况下更新对象数组

时间:2018-09-18 04:16:51

标签: arrays mongodb mongoose

在这里,我要为对象数组中的所有元素更新1个字段。如何只用一个查询来更新该字段,而又不循环和更新每个元素,也不扫描整个数据库并进行匹配?

我的模型架构:

let NameCardSchema = mongoose.Schema({
    fullname: {
        type: String,
        required: true
    },
    occupation: {
        type: String,
        default: null
    },
    company: {
        type: String,
        default: null,
    },
    position: {
        type: String,
        default: null,
    },
    userID: [String] // field to update
});

样本数据:

User:
    _id:5b8e4c6a879ac54ee0f30bb3
    username:"Duc"

Namecard array:
[
    namecard1:
        _id:5b9615c6b157af5afc8ce426
        occupation:null
        company:"KIS"
        position:"Developer"
        fullname:"Duc Nguyen Trung"
        userID:"5b9a173f0749c52b583818ec"

    namecard2:
        _id:5b96162fb157af5afc8ce428
        occupation:null
        company:"KIS"
        position:"Developer"
        fullname:"Hieu Vuong"
        userID:"5b9a16700749c52b583818ea"
]

预期结果:

[
    namecard1:
        _id:5b9615c6b157af5afc8ce426
        occupation:null
        company:"KIS"
        position:"Developer"
        fullname:"Duc Nguyen Trung"
        userID:"5b9a173f0749c52b583818ec", "5b8e4c6a879ac54ee0f30bb3" // username Duc's ID added

    namecard2:
        _id:5b96162fb157af5afc8ce428
        occupation:null
        company:"KIS"
        position:"Developer"
        fullname:"Hieu Vuong"
        userID:"5b9a16700749c52b583818ea", "5b8e4c6a879ac54ee0f30bb3" // username Duc's ID added
]

1 个答案:

答案 0 :(得分:1)

要将新条目添加到所有文档的userID数组中,只需执行以下操作:

db.collection.updateMany({ /* no filter */ }, { $push: { "Namecards.$[].userID": "5b8e4c6a879ac54ee0f30bb3" } })