【问题标题】:Increment nested field value in mongodb if exists or create nested fields如果存在,则在 mongodb 中增加嵌套字段值或创建嵌套字段
【发布时间】:2020-02-17 17:43:49
【问题描述】:

如果存在,我需要增加多级嵌套字段值或创建完整的嵌套字段对象结构。

我的文档结构

Doc1 {
_id:ObjectId(),
myField: {
  nested:{
      x: 5,
      y: 10,
      z: 20
  }
 }
}

目标说明:我需要一种方法来编写单个查询:

  • 如果 myField 存在:增加我的嵌套字段的值 myField.nested.x 10。
  • 如果 myField 不存在:使用与 Doc1 中给定的初始值相同的初始值创建以下字段。

尝试及解释

 db.collection('collectionName').findOneAndUpdate(
    {_id:"userId","myField" : { $exists : true }},
    {$inc:{'myField.nested.x':10}
 })

这样,如果嵌套字段存在,我可以递增嵌套字段,但如果不存在,我无法将 myField 设置为与 Doc1 相同。

虽然,我可以在 NodeJs 回调中的响应后使用另一个查询来实现我所需的行为。但我需要在单个查询中提供一些优雅的解决方案。

我使用的是 MongoDB 4.0.4 版,在此先感谢。

【问题讨论】:

  • 如果该字段不存在,$inc 创建该字段并将该字段设置为指定值。 db.collection('collectionName').findOneAndUpdate({_id:"userId"}, {$inc:{'myField.nested.x':10} })

标签: node.js mongodb mongodb-query increment subdocument


【解决方案1】:

试试这个查询

如果该字段不存在,$inc 将创建该字段并将该字段设置为指定值。

db.collection('collectionName').findOneAndUpdate({_id:"userId"},
{$inc:{'myField.nested.x':10}
})

【讨论】:

    猜你喜欢
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多