首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoDB缝合-当使用update递增时,如何将数据类型保持为整型(而不会更改为双精度)?

MongoDB缝合-当使用update递增时,如何将数据类型保持为整型(而不会更改为双精度)?
EN

Stack Overflow用户
提问于 2020-02-10 12:47:04
回答 1查看 155关注 0票数 0

我在mongodb中使用缝合。在缝合中,我编写了一个用于递增和递减的nodejs函数。

代码语言:javascript
复制
if(changeEvent.fullDocument.type == 'article' || changeEvent.fullDocument.type == 'poll' ) {
  context.functions.execute("notifyTopic", "article-created", changeEvent.fullDocument);
  var communities = context.services.get("mongodb-atlas").db("utilo").collection("communities");
  communities.updateOne(
    {_id:changeEvent.fullDocument.community},
    {$inc: {"summary.postCount":NumberInt(1)}, $currentDate: {"summary.lastActivity":true} }
  )
} else if (changeEvent.fullDocument.type == 'comment') {
  context.functions.execute("notifyTopic", "comment-created", changeEvent.fullDocument);
  var posts = context.services.get("mongodb-atlas").db("utilo").collection("posts");
  posts.updateOne(
    {_id:changeEvent.fullDocument.root},
    {$inc: {"summary.commentCount":1}, $currentDate: {"summary.lastActivity":true} }
  )

现在我已经执行了这个函数,summary.postCount的值从整型转换为双精度型,我也是这样使用NumberInt的。

代码语言:javascript
复制
 posts.updateOne(
    {_id:changeEvent.fullDocument.root},
    {$inc: {"summary.commentCount":NumberInt(1)}, $currentDate: {"summary.lastActivity":true} }
  )

communities.updateOne(
    {_id:changeEvent.fullDocument.community},
    {$inc: {"summary.postCount":NumberInt(-1)}, $currentDate: {"summary.lastActivity":true} }
  )

这不是工作事件我也提到了"summary.$.postCount“,但没有任何用处。

我只需要增量/减量值和整型数据类型。请帮我解决这个问题。提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2020-02-10 14:41:35

请检查以下内容:

  1. ,你是对的,当你这么做的时候,{$inc: {"summary.commentCount":1},它会把任何Int32字段转换成Double

  1. ,所以一开始你应该试试{$inc: {"summary.commentCount":NumberInt(1)}。现在,它已经被转换为

,用于进一步的查询,使用步骤2是无用的。您需要将字段设置回原始数据类型,然后继续执行进一步的操作。

MongoDB v > 4.2上,可以在update()中运行聚合管道,将字段postCount上的所有文档从double更新为int。

代码语言:javascript
复制
db.collection.update(
    {},
    [
        { $set: { postCount: { $toInt: '$postCount' } } }
    ], false, true // 1) false is {upsert : false}, 2) is {multi : true}
)

如果您使用的是MongoDB v < 4.2,您可能需要找到一种方法来更新所有文档的各自的值,也许可以使用.bulkWrite().updateMany()读取、操作数据和更新。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60144231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档