$set in MongoDB :未按预期工作
$set in MongoDB : Not working as intended
我的数据库中有以下文档:
{
....
"key": "val1",
....
"array" :[
{
"k":"v1",
"rejected":"0"
},
{
"k":"v2",
"rejected":"0"
}
]
.....
}
现在基本上我想设置 "rejected":"1" for ("key":"val1" && array[i]."k":"v1" ).
我写的API调用是:
var val1="val1";
var v1="v1";
request.put('https://api.mlab.com/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 没有编辑所需的字段,而是在文档末尾附加了一个新字段:
{
....
"key": "val1",
....
"array" :[
{
"k":"v1",
"rejected":"0"
},
{
"k":"v2",
"rejected":"0"
}
]
.....
"rejected":"1"
}
假设您的 json 对象被称为 array...阅读 mongodb.Then 中的位置运算符,这将更新您的数组元素
Object.update(
{'array.key': val1},
{$set: {'array.$. rejected': 1}},
function(err, count) { ... });
在这种情况下使用 db.collection.update
Mongodbshell查询
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}
);
更新查询分为三个部分
首先是我们必须给出的匹配部分
"key":"val1" and "array.k": "v1"
第二部分是设置更新值
使用$set和位置运算符,设置要更新的值
此处用于匹配 array.k 更新被拒绝为“1”
最后一部分是指定是否有多个文档匹配条件然后更新所有匹配的文档
我的数据库中有以下文档:
{
....
"key": "val1",
....
"array" :[
{
"k":"v1",
"rejected":"0"
},
{
"k":"v2",
"rejected":"0"
}
]
.....
}
现在基本上我想设置 "rejected":"1" for ("key":"val1" && array[i]."k":"v1" ).
我写的API调用是:
var val1="val1";
var v1="v1";
request.put('https://api.mlab.com/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 没有编辑所需的字段,而是在文档末尾附加了一个新字段:
{
....
"key": "val1",
....
"array" :[
{
"k":"v1",
"rejected":"0"
},
{
"k":"v2",
"rejected":"0"
}
]
.....
"rejected":"1"
}
假设您的 json 对象被称为 array...阅读 mongodb.Then 中的位置运算符,这将更新您的数组元素
Object.update(
{'array.key': val1},
{$set: {'array.$. rejected': 1}},
function(err, count) { ... });
在这种情况下使用 db.collection.update
Mongodbshell查询
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}
);
更新查询分为三个部分
首先是我们必须给出的匹配部分
"key":"val1" and "array.k": "v1"
第二部分是设置更新值
使用$set和位置运算符,设置要更新的值 此处用于匹配 array.k 更新被拒绝为“1”
最后一部分是指定是否有多个文档匹配条件然后更新所有匹配的文档