MongoDB中的$ set:未按预期工作 [英] $set in MongoDB : Not working as intended

查看:123
本文介绍了MongoDB中的$ set:未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有以下文档:

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('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而不是编辑必填字段,而是在文档末尾添加了一个新字段:

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:未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆