【问题标题】:MongoDB "Update Where" like in MySQL but for arraysMongoDB“更新位置”,就像在 MySQL 中一样,但用于数组
【发布时间】:2015-04-28 20:23:48
【问题描述】:

我想更改 MongoDB NoSQL 数据集中数组中元素的字段。但是在更新时,由于并行化,我不知道该元素具有哪个索引。我所知道的是存储在该元素内部的一些值。

我的数据

course = {
    _id: ObjectId("some-id"),
    someOtherFields: {
        ...
    }
    myList: [
        {
            uid: ObjectId("some-user-id-1"),
            someField: "value to change",
            ...
        },
        ...
    ]
}

查询以显示具有特定 uid 的所有“课程”的 myList 条目看起来像

我的查询

db.courses.find(
  {"myList": {"$elemMatch":{"uid":"my-uid-to-find"}}}, 
  {"_id":true, "someOtherField":true, "myList.$":true}
)

问题

问题是我怎样才能只用查询更新这一行而不用 知道它的索引。

我想更改 someFieldmyList.$ 哪里 myList.$.uid = someIdToFind

【问题讨论】:

  • 你没有在你的数据中定义mailinglist
  • 哎呀,抱歉,我的列表已经更新了

标签: mongodb


【解决方案1】:

在这种情况下,首先您应该使用elemMatch 将给定数组值的所有匹配条件放入更新查询中,就像在您的find 语句中一样。

然后在更新中使用mongo positional operator $,更新查询如下:

db.collectionName.update({
  "myList": {
    "$elemMatch": {
      "uid": "your given ObjectId" // set here ObjectId to find matching element in array
    }
  }
}, {
  "$set": {
    "myList.$.someField": "your updated value" // use mongo postional operator "$" to iterate over array 
  }
}) 

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多