问题
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 :
- You're right when you do this
{$inc: {"summary.commentCount":1}
it would convert anyInt32
field toDouble
. - So at first you should've tried
{$inc: {"summary.commentCount":NumberInt(1)}
. - 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