MongoDB“更新地点"就像在 MySQL 中一样,但对于数组 [英] MongoDB "Update Where" like in MySQL but for arrays

查看:52
本文介绍了MongoDB“更新地点"就像在 MySQL 中一样,但对于数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to change a field of an element inside an array in a MongoDB NoSQL dataset. But at the time of the update, I do not know which index the element has due to parallelisation. What I do know are some values that are stored inside of that element.

我的数据

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

查询以显示具有特定 uid 的所有课程"的 myList 条目

Query to show all "courses"s myList entries with a specific uid look like

我的查询

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

问题

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

the question is how can I update only this row with a query without knowing its index.

我想改变 myList.$someField 其中myList.$.uid = someIdToFind

I want to change someField of myList.$ where myList.$.uid = someIdToFind

推荐答案

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

In this case first you should put all matching criteria of given array values in update query using elemMatch as same like in your find statement.

然后在更新中使用 mongo 位置运算符 $ 所以更新查询如下:

Then use mongo positional operator $ in update so update query as below :

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 
  }
}) 

这篇关于MongoDB“更新地点"就像在 MySQL 中一样,但对于数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆