在mongoDb中更新数组对象的问题

时间:2014-05-19 05:38:42

标签: mongodb mongoose

我正在尝试根据条件更新Array对象。以下是我的情景: -

enter image description here

我想将状态从当前状态更新为存档。

我已经尝试了好几个小时,但仍然没有运气。像这样: -

db.user.update({
    'injury._id': ObjectId("5374cb4d1e0386c02800006a"),
    'injury.injurydata.locationaddressinjury': {
        $elemMatch: {
            'status': 'current'
        }
    }
}, {
    $set: {
        'injury.injurydata.locationaddressinjury.status': 'archive'
    }
})

1 个答案:

答案 0 :(得分:0)

图片使您难以阅读数据结构。但我想你正在寻找的更新将是这样的:

db.user.update({
    'injury._id': ObjectId("5374cb4d1e0386c02800006a"),
    'injury.injurydata.locationaddressinjury': {
        $elemMatch: {
            'status': 'current'
        }
    }
}, {
    $set: {
        'injury.injurydata.locationaddressinjury.$.status': 'archive'
    }
});

$会引用您找到的元素。如果您正在寻找一种方法一次更新所有元素。我担心$ elemMatch会匹配满足你条件的第一个元素。