我的数据库中有以下文档:
I have the following document in my DB :
{ .... "key": "val1", .... "array" :[ { "k":"v1", "rejected":"0" }, { "k":"v2", "rejected":"0" } ] ..... }现在基本上,我想将"rejected":"1"设置为("key":"val1"&& array [i]."k":"v1")./em>
我编写的API调用是:
The API call that I have written is :
var val1="val1"; var v1="v1"; request.put('api.mlab/api/1/databases/DB/collections/doc?q={"key": "'+val1+'","array.k":"'+v1+'"}&apiKey=.....', { json: { "$set": {"rejected": "1"} } }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("----->Insertion"+body); return res.status(200).send("[{\"status\":\"success\"}]"); } else {console.log(JSON.stringify(response));} });但是API而不是编辑必填字段,而是在文档末尾添加了一个新字段:
But the API instead of editing the needed field,it appends a new field at the end of document:
{ .... "key": "val1", .... "array" :[ { "k":"v1", "rejected":"0" }, { "k":"v2", "rejected":"0" } ] ..... "rejected":"1" }推荐答案
在这种情况下,请使用 db.collection.update
In this case use db.collection.update
Mongodb shell查询
Mongodb shell query
If there is only one matching document db.collection_name.update( {key:"val1", "array.k":"v1"}, {$set:{"array.$.rejected":"1"}} ); If there are multiple documents matching the criteria then use the below query with multi:true db.collection_name.update( {key:"val1", "array.k":"v1"}, {$set:{"array.$.rejected":"1"}}, {multi:true} );更新查询包含三个部分
首先是我们必须提供的匹配部分
First is the matching part where we have to give
"key":"val1" and "array.k": "v1"第二部分是设置更新值
使用$ set和位置运算符,设置要更新的值 这里匹配的array.k更新被拒绝为"1"
Using $set and positional operator, set the value to be updated here for matching array.k update rejected as "1"
最后一部分是指定多个文档是否符合条件,然后更新所有匹配的文档
Final part is to specify if multiple documents are matching the criteria then update all the matching documents
更多推荐
MongoDB中的$ set:未按预期工作
发布评论