如何更新mongodb中的数组元素

时间:2016-08-29 11:36:41

标签: angularjs node.js mongodb

我在mongoDB中有数据,如下所示

{
  "_id": ObjectId("57c40e405e62b1f02c445ccc"),
  "sharedPersonId": ObjectId("570dec75cf30bf4c09679deb"),
  "notificationDetails": [
     {
       "userId": "57443657ee5b5ccc30c4e6f8",
       "userName": "Kevin",
       "isRed": true 
     } 
   ] 
}

现在我想将isRed值更新为false如何为此编写查询。我尝试了类似下面的内容

var updateIsRedField = function(db, callback) {
    db.collection('notifications').update({_id:notificationId},
    {
        $set: { "notificationDetails.$": {isRed: false}},
    }, function(err, results) {
        callback();
    });
};

MongoClient.connect(config.database, function(err, db) {
    assert.equal(null, err);
    updateIsRedField(db, function() {
        db.close();
    });
    return res.json({});
});

1 个答案:

答案 0 :(得分:3)

由于位置 $ 运算符充当与查询文档匹配的第一个元素的占位符,并且数组字段必须作为查询文档的一部分出现,因此查询{{ 1}}对于让 $ 运算符正常工作至关重要:

{ "notificationDetails.isRed": true }