如何在一个查询中在MongoDB中的多个字段中递增价值和多个文档

发布于 2025-02-09 03:34:08 字数 726 浏览 0 评论 0原文

我有一个代表课程的对象,

 {
    "_id": "62ad8ac4a5523541d78df217",
    "lessonID": "35d02fc5-94dd-48e7-a315-7dcea6ac6806",
    "teachers": [
        "629232d2fc8fa8646b21cf3d"
    ],
    "students": [
        "62924d0a6055ad4d2533577b"
    ],
    "subject": "English",
    "start": 1655515800000,
    "end": 1655517600000,
    "roomNumber": "3",
    "venue": "Elmwood Park",
    "attendance": [
        "62924d0a6055ad4d2533577b"
    ],
    "paid": false,
    "__v": 0
},       
           

我要做的是找到具有相同“ crenthId”的所有文档,然后更新“ start”和“ end”(时间戳)。

值一定数量

想在我坐在上面坐着的

  • 每个文档
  • 减少
  • 上增加或 映射的文档阵列

听起来极低效率(如果任何步骤失败,则会导致重复或丢失数据)……必须有更好的方法来做到这一点。

I have an object which is representing a lesson

 {
    "_id": "62ad8ac4a5523541d78df217",
    "lessonID": "35d02fc5-94dd-48e7-a315-7dcea6ac6806",
    "teachers": [
        "629232d2fc8fa8646b21cf3d"
    ],
    "students": [
        "62924d0a6055ad4d2533577b"
    ],
    "subject": "English",
    "start": 1655515800000,
    "end": 1655517600000,
    "roomNumber": "3",
    "venue": "Elmwood Park",
    "attendance": [
        "62924d0a6055ad4d2533577b"
    ],
    "paid": false,
    "__v": 0
},       
           

what i'm trying to do is to find all documents with the same "lessonID" and update "start" and "end" (timestamps).

I'd like to increment or decrease values by a certain amount on every document

I've been sitting on it for a while and I thought about doing this:

  • finding all documents that match my query
  • deleting all found documents
  • mapping through the array
  • inserting the mapped array of documents

it sounds extremely inefficient tho (and it causes duplicate or loss of data if any of the steps fail)... there must be a better way to do that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏末染殇 2025-02-16 03:34:08

正如@gibbs所建议的那样,只需使用$ inc

db.collection.update({
  "lessonID": "35d02fc5-94dd-48e7-a315-7dcea6ac6806"
},
{
  $inc: {start: amountStartInc, end: amountEndInc}
})

请参阅其在

As @Gibbs suggested, simply use $inc:

db.collection.update({
  "lessonID": "35d02fc5-94dd-48e7-a315-7dcea6ac6806"
},
{
  $inc: {start: amountStartInc, end: amountEndInc}
})

See how it works on the playground example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文