How to decrement like $dec?
Asked Answered
G

7

50

In the Meteor leaderboard example there is this line:

  Players.update(Session.get("selected_player"), {$inc: {score: 5}});

How can I gracefully decrement the same field? Sadly, there is no $dec.

Glazing answered 25/10, 2014 at 7:51 Comment(0)
A
134

MongoDB allows you to increment by negative values:

$inc: {score: -1}
Antrorse answered 25/10, 2014 at 7:53 Comment(0)
K
8

From the MongoDB docs (linked to from the Meteor docs): The $inc update operator accepts positive and negative values. A negative value effectively decrements the specified field.

http://docs.mongodb.org/manual/reference/operator/update/inc/

Kurtiskurtosis answered 25/10, 2014 at 8:57 Comment(0)
H
4

You can apply this code:

$inc: {
  score: -1
}

apply negative values (-1, -3, -5 and so on ) for decrement value.

Hancock answered 28/6, 2022 at 6:25 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Rianon
R
2

There is no need of something like $dec. A negative value effectively decrements the specified field. For example using (-value):

Players.update(Session.get("selected_player"), {$inc: {score: -value}});
Rai answered 29/5, 2020 at 21:43 Comment(0)
M
2
Players.update(Session.get("selected_player"), {$inc: {score: -1}});

you can simply use negative value (ex : -1, -2, -3, .....) for decrement value in mongo collection

Melicent answered 28/12, 2021 at 12:19 Comment(0)
K
0

Use the $inc update operator to decrement a field's value by providing a negative value.

db.products.updateOne(
  { name: "Laptop" },
  { $inc: { quantity: -5 } }
)
Kelso answered 16/5 at 6:40 Comment(0)
T
-1

JS

db.test.update({id: "zxf"}, {$inc: {intValue: NumberInt(-1)}});

Java

Update update = new Update().inc(field, -1);

Type answered 24/5, 2018 at 9:14 Comment(1)
Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.Painless

© 2022 - 2024 — McMap. All rights reserved.