0

I want to create a dynamic query that updates a document in a Mongodb collection based on the user input. The user may update some or all the fields in the document. The document also contains an array to which the user is allowed to add elements. I know how to construct simple dynamic queries for 'find' queries but struggling with an update query which might have $set, $addToSet, $pull etc elements.

My final query will look like this:

Col.update({'_id' : bookId}, {$inc : {'total_count' : 1}, $set: {'name': name}, $addToSet : {'reviewed_by' : user}})

All the elements in the update part of the query will be added conditionally.

I have searched on SO and elsewhere and I don't see any example that shows how to accomplish this. Hopefully many others will also find this useful.

1 Answer 1

2

Not sure I'm understanding you correctly, but it sounds like what you're looking for is really just javascript...

var update = {};
if( ... ) // do increment?
    update['$inc'] = {'total_count': 1};

// and so on...

if(Object.keys(update).length)
    Col.update({'_id': bookId}, update);
Sign up to request clarification or add additional context in comments.

2 Comments

That makes sense! I was thinking it was going to be much complicated. Many thanks!
One more question Zane. If it was $set instead of $inc in your sample code above, and I wanted to update multiple fields using the same $set, how would I do that?

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.