MongoDB:如何只更新文档中的一个元素? [英] MongoDB: how to update only one element in the document?

查看:74
本文介绍了MongoDB:如何只更新文档中的一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想更新文档中的一个元素以使用 put 请求

I want to updates only one element in the document to use put request

我试过了

PUT localhost:3000/api/memo/5b8e382d61984255d879f872

PUT localhost:3000/api/memo/5b8e382d61984255d879f872

{
    text: "updated!"
{

但是,它像这样更新

{
    text: "updated!",
    imgUrl: null,
    tag: null,
    ...
}

有没有办法更新文档中的一个元素?

Is there a way to updates one element in document?

await Memo.where('_id')
      .equals(req.params.id)
      .updateOne({
        imgUrl: req.body.imgUrl,
        text: req.body.text,
        tag: req.body.tag,
        user: req.body.user,
        loc: req.body.loc
      })

推荐答案

您可以使用以下解决方案仅更新一个元素:

You can use the following solution to update only one element:

Memo.updateOne(
  { "_id" : ObjectId("5b8e83957d56e802274d6") },
  { $set: { "text" : "updated" } });

UpdateOne() 更新集合中与过滤器匹配的第一个匹配文档.上述查询操作更新文本为已更新"的单个文档.

UpdateOne() updates the first matching document in the collection that matches the filter.The above query operation updates a single document where text: "updated".

该操作可以替换现有文档或更新现有文档中的特定字段.

The operation can either replace an existing document or update specific fields in an existing document.

这篇关于MongoDB:如何只更新文档中的一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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