2017-05-24 147 views
0
{ 
    "_id" : ObjectId("5925e2213daf48359cb5429e"), 
    "email" : "[email protected]", 
    "firstname" : "test3", 
    "friends" : [ 
     { 
      "friend_email" : "[email protected]", 
      "status" : 1, 
      "fname" : "test2" 
     }, 
     { 
      "friend_email" : "[email protected]", 
      "status" : 1, 
      "fname" : "test1" 
     } 
    ] 
} 

我的数据库看起来像上面。 “朋友”可以在里面有很多条目。我必须用(假设)friend_email =“[email protected]”和email =“[email protected]”搜索特定条目(取决于变量值),并将其特定字段“状态”更改为0. I正确写了这以下的更新查询,嵌套的文档更新MongoDB

collection_temp.update({ 

     "email": email([email protected]) ,  
     "friends" : 
     {$elemMatch : 
       {"friend_email" : friend_req_sent_to ([email protected])} 
     }}, 
     {"$set": 
       {"friends.$.status" : 0} 
    }, 

    function(err, result) { 
     if (result) { 
      console.log("SUCCESS"); 

     } else { 
      console.log("FAIL"); 
     } 
    }); 

我的查询运行,但是状态字段没有发生变化....请告诉我,我错了?

+0

你可以尝试单独运行查询,然后调用各自的功能?也许容易那样? –

+0

奇怪我对你的查询做了一个快速测试,它工作正常。你如何验证财产“状态”的价值没有改变?你介意仔细检查你的集合名称,在代码中描述一个与db中的内容相关的名称。 –

+0

@JayNirgudkar有没有人解决你的问题?如果是这样,请您接受最好的答案(点击下面的选中标记)。这将有助于其他遇到您的问题的用户迅速找到接受的答案,并且还会给出15个代表。指向作者(: – Danziger

回答

1

查询工作正常,您可能会返回您正在使用的这些功能(emailfriend_req_sent_to)的错误值。

与所有status字段设置为1,运行:

db.test.update({ 
    email: "[email protected]", 
    friends: { $elemMatch: { friend_email: "[email protected]" } } 
}, { $set: { "friends.$.status": 0 } }) 

返回:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 

如果我有find检查我可以看到文件了适当的更新。