MongoDB中的$ set:未按预期工作

编程入门 行业动态 更新时间:2024-10-27 17:18:10
本文介绍了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('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:未按预期工作

本文发布于:2023-07-27 13:49:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222713.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未按   工作   MongoDB   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!