【问题标题】:In MongoDB, how do I find and update a particular array element?在 MongoDB 中,如何查找和更新特定的数组元素?
【发布时间】:2015-06-05 13:32:21
【问题描述】:

假设我有以下 MongoDB 集合,我想查找 ratings.byijk 的所有文档并将其评级更新为 6。

换句话说,将{ by: "ijk", rating: 4 } 更新为{ by: "ijk", rating: 6 }。问题是我不知道这样的数组元素的索引。

{
  _id: 1,
  item: "TBD",
  stock: 0,
  info: { publisher: "1111", pages: 430 },
  tags: [ "technology", "computer" ],
  ratings: [ { by: "ijk", rating: 4 }, { by: "lmn", rating: 5 } ],
  reorder: false
}

我的问题:我应该如何编写db.collection.update() 函数?这是我失败的尝试:

db.collection.update({
    ratings.by: {
        $elemMatch: {
            $eq: 'ijk'
        }
    }
}, {
    $set: {
        // don't know which index to set. How should I modify this line?
        ratings.rating: 6
    }
}, {
    multi: true
});

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    使用 $ positional operator 标识要更新的数组中的元素,而无需明确指定该元素在数组中的位置:

    db.collection.update(
        { "ratings.by": "ijk" }, 
        { "$set": { "ratings.$.rating": 6 }},
        { "multi": true }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-11
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2017-01-05
      相关资源
      最近更新 更多