users.findOneAndUpdate

an anonymous user · February 03, 2024
const transaction = {
    type: 'expense',
    amount: 90,
    wallet: 'bitcoin'
};
db.createCollection("users");
db.users.insertOne(
    {  
        _id: ObjectId("65bea0174ac627b1ae79b664"),
        username: "bob",
        wallets:[
            {
                name: 'bitcoin',
                balance: 100  
            },
            {
                name: 'eth',
                balance: 75  
            }
        ],
        transactions: [
            {
                type: 'expense',
                amount: 25,
                wallet: 'eth'
            },
        ]
    }
);
db.users.findOneAndUpdate(
    {
        _id: ObjectId("65bea0174ac627b1ae79b664"), 
        'wallets.name': transaction.wallet
    },
    {
        $push: {
            'transactions': transaction
        },
        $inc: {
            'wallets.$.balance': -transaction.amount    
        }
    }  
);
db.users.find();
Output

Comments

Please sign up or log in to contribute to the discussion.