【问题标题】:MongoDb $set value of field after identifying the object within the arrayMongoDb $set 识别数组中的对象后的字段值
【发布时间】:2015-04-16 22:08:07
【问题描述】:

在 Mongo $set 操作中,如何通过将字段 'idGen' 匹配到名为 'id' 的变量来识别 array 中的特定对象。那么,通过将'idGen' 与该对象中的变量'id' 匹配,我如何将value 变量设置为该对象中名为fieldStr 的字段?

在服务器上,我通过像这样匹配 userId 来找到集合。

var id
var fieldStr
var userId = this.userId

我试过了:

Collection.update(
{'createdBy': userId, 'array.$.idGen': id},
{$set: 
      {'array.$.fieldStr': value}
})

如您所见,'idGen' 字段是数组中每个对象的唯一字段。

【问题讨论】:

  • 对不起,我想通了。我不知道我是否应该删除我的问题。

标签: mongodb mongodb-query


【解决方案1】:
Collection.update({'createdBy': userId, 'array': {$elemMatch: {idGen': id}}}, {$set: {'array.$.fieldStr': value}})

elemMatch 将数组中的对象与“id”变量 idGen 匹配到“id”变量。 $ 是我的占位符,用于定位“fieldStr”字段,然后我可以将值设置为。

【讨论】:

    猜你喜欢
    • 2020-05-08
    • 2020-04-28
    • 2016-08-03
    • 1970-01-01
    • 2023-01-23
    • 1970-01-01
    • 2021-07-01
    • 2020-07-04
    • 1970-01-01
    相关资源
    最近更新 更多