Reputation: 2767
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.
Upvotes: 0
Views: 1535
Reputation: 14954
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);
Upvotes: 2