MongoDB Stitch - How to keep datatype to int (without changing to double) when incremented with update?

▼魔方 西西 提交于 2021-02-11 17:51:17

问题


I am using stitch in mongodb. In stitch, i write one nodejs function for increment and decrements purpose.

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

Now i have executed this function, the summary.postCount value converted from int to Double, I am usnig NumberInt also like this.

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

this was not working event i have mentioned "summary.$.postCount" also, but there is no use.

I need the Increment/decrements values and datatype integer only. Please help me with the solution. Thanks in advance.


回答1:


Check this :

  1. You're right when you do this {$inc: {"summary.commentCount":1} it would convert any Int32 field to Double.
  2. So at first you should've tried {$inc: {"summary.commentCount":NumberInt(1)}.
  3. Now it's already converted to double for further queries using step 2 is useless. You need to set your field back to original data type & then go ahead with your further operations.

On MongoDB v > 4.2, you can run an aggregation pipeline in update() to update all docs from double to int on field postCount.

db.collection.update(
    {},
    [
        { $set: { postCount: { $toInt: '$postCount' } } }
    ], false, true // 1) false is {upsert : false}, 2) is {multi : true}
)

If you're using MongoDB v < 4.2 you might need to find a way to update all docs with their respective values, maybe read, manipulate data & update using .bulkWrite() or .updateMany().



来源:https://stackoverflow.com/questions/60144231/mongodb-stitch-how-to-keep-datatype-to-int-without-changing-to-double-when-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!