1

I have following nested object to update after some conditions.based on the condition finally iwant to update promotional or transactional value

{
    "_id" : "XX1",   
    "credit" : {
        "sms" : {
            "credit" : {
                "promotional" : 0,
                "transactional" : 1231
            }
        },
        "viber" : {
            "credit" : {
                "promotional" : 10,
                "transactional" : 50
            }
        },
        "whatsapp" : {
            "credit" : {
                "promotional" : 30,
                "transactional" : 40
            },            
        }
    },
}

conditions will based on the passing variable values

 accountId = "XX1",
 channel = "sms",
 messageType = "promotional",
 credit = 150

these are the conditions should check befor update

  • _id should match with accountId
  • if channel='sms',it should select credit.sms
  • if messageType = "promotional" then check promotional value is greater than to credit or not
  • if it is greater than to credit value (credit.sms.credt.promotional) should update with : (credit.sms.credt.promotional)-credit
1
  • what is your MongoDB version ? Commented Apr 17, 2020 at 19:44

1 Answer 1

2

You can use Computed property name and $inc operator to do it. Something like:

YourModel.findOneAndUpdate(
  { _id: accountId, [`credit.${channel}.credit.${messageType}`]: { $gte: credit } },
  { $inc: { [`credit.${channel}.credit.${messageType}`]: -credit} }
)
Sign up to request clarification or add additional context in comments.

1 Comment

thanks it works for greater than values.also if it is less than to credit,i want to assign current credit.${channel}.credit.${messageType} into variable and update document record into 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.