简体   繁体   English

如何在一次查询中对mongodb中的多个字段和多个文档进行递增

[英]How to increment value in multiple fields and multiple documents in mongodb in one query

I have an object which is representing a lesson我有一个代表课程的 object

 {
    "_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).我想要做的是找到所有具有相同“lessonID”的文档并更新“开始”和“结束”(时间戳)。

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.这听起来效率极低(如果任何步骤失败,它会导致数据重复或丢失)......必须有更好的方法来做到这一点。

As @Gibbs suggested, simply use $inc :正如@Gibbs 建议的那样,只需使用$inc

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

See how it works on the playground exampleplayground 示例中查看它是如何工作的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM