【问题标题】:MongoKitten support for $inc modifierMongoKitten 支持 $inc 修饰符
【发布时间】:2018-05-09 09:58:09
【问题描述】:

我想通过 Vapor 和 MongoKitten 更新 MongoDB 中的自动增量字段。不一定是唯一键。

目标是使用 $inc 修饰符使其成为单个原子操作并一次性获得返回的递增结果。

MongoKitten 是否支持此操作?

我可以做到这一点吗?使用 findAndUpdate 方法?

如果是,这将是什么示例语法?

【问题讨论】:

    标签: mongodb vapor mongokitten


    【解决方案1】:

    使用 MongoKitten,您可以使用 Collection 上的 findAndUpdate 函数来执行此操作。输入应该是一个查询(除非您想增加集合中的所有实体)和更新文档的 with 参数。

    // The query used to find the document to increment
    let query: Query = "_id" == ...
    

    在更新文档中,你可以像这样使用$inc operator

    let updateDoc: Document = ["$inc": ["myKey": 1]]
    

    这将通过增加 1 来更新“myKey”

    let updated = try collection.findAndUpdate(query, with: updateDoc)
    

    updated 文档将包含更新之前的文档,因此如果 myKey 的值为 3。在此查询之后它将递增到 4,但您会收到值为 3 的文档。

    要更改此设置,您可以更改 returnedDocument 参数(默认为 .old

    let updated = try collection.findAndUpdate(query, with: updateDoc, returnedDocument: .new)
    

    最后,如果您关心优化或只是发现通常会限制返回的结果,您应该考虑添加投影。 Projections 向数据库指出您对哪些字段感兴趣和不感兴趣。

    您可以将它与findAndUpdate 一起使用,以确保仅返回相关字段,即本例中的myKey 整数值。

    let updated = try collection.findAndUpdate(query, with: updateDoc, returnedDocument: .new)
    

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 1970-01-01
      • 2021-12-07
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多