【问题标题】:MongoDB push data to specific array elementMongoDB 将数据推送到特定的数组元素
【发布时间】:2017-03-16 18:10:33
【问题描述】:

大家好,我正在做流星 mongo db,我使用 findAndModify 包

Ips.findAndModify({

      //Find the desired document based on specified criteria
      query: {
        "ipAdr": clientIp,
        connections: {
          $elemMatch: {
            connID: clientConnId
          }
        }
      },

      //Update only the elements of the array where the specified criteria matches
      update: {
        $push: {
          'connections': {
            vid: result.data.vid,
            firstName: result.data.properties.firstname.value,
            lastName: result.data.properties.lastname.value
        }
      }
    }); //Ips.findAndModify

所以我找到了我需要的元素,但是我的信息被推送到整个连接数组,但我想将我的信息推送到那个特定的元素中。我应该在这里做什么?我试过了

$push: {
              'connections.$': {
                vid: result.data.vid,

但它给出了错误。 请帮忙。

【问题讨论】:

  • 你遇到了什么错误??

标签: arrays node.js mongodb meteor


【解决方案1】:

您不需要在此处使用 $push 运算符,因为它会向数组添加一个新元素,而您需要修改一个已经在数组中的元素,试试 $set 操作符更新如下:

update: {
        $set: {
          'connections.$.vid': result.data.vid,
          'connections.$.firstName': result.data.properties.firstname.value,
          'connections.$.lastName': result.data.properties.lastname.value
        }
      }

请注意,这样您只会更改数组中满足 $elemMatch 语句条件的一个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2021-08-09
    • 2018-04-11
    • 2013-09-27
    • 1970-01-01
    • 2016-01-20
    • 2021-06-27
    相关资源
    最近更新 更多