mongodb - 如何更新 mongo 对象

标签 mongodb mongodb-query

我需要更新我的 mongo 以下文档是我的架构

{ "_id" : 7742, "current_count" : { "abc" : 6 } }

并且需要更新 current_count 对象,其中我不知道 key ,如果出现相同的 key ,则需要替换如下所示的值。

{ "_id" : 7742, "current_count" : { "abc" : 6 ,"xyz":10} }

如果"abc"遇到只需替换它的值即可,

 { "_id" : 7742, "current_count" : { "abc" : 456 ,"xyz":10} }

最佳答案

您只需要循环获取作为有效负载获得的键,并需要创建动态键值对并将其设置为 $set 运算符

const data = {
  abc: 456,
  xyz: 10
}
const object = {}

for (var key in data) {
  object[`current_count.${key}`] = data[key]
}

输出为

current_count.abc: 456
current_count.xyz: 10

然后将其放入您的查询中

const query = { "_id" : 7742 };
const update = { "$set": object };

await Model.findOneAndUpdate(query, update)

关于mongodb - 如何更新 mongo 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56250181/

相关文章:

python - 如果文档存在,MongoDB 返回 True

mongodb - 如何停止在 mongodb 集合中插入重复文档

node.js - 选择字段值作为数组 mongoose/mongodb 聚合

mongodb - 减去 MongoDB 中的组聚合值

javascript - mongo $where 返回所有内容

MongoDB 聚合 : How to get total records count?

javascript - MongoDB:更新集合中的数组项不起作用

node.js - MongoDB 更新 $pull 多个数组中的文档

MongoDB 可选唯一索引

java - 如何使用文档和 mongo 聚合将 mongo shell 代码转换为 java 代码