Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update mongo db documents with regex

Tags:

mongodb

I need to find all the documents in mongodb that have keywords that start with number 1-9, then add a '+' in front of the keyword, I can easily find the documents but cannot figure out how to update them.

I tried this one, but it doesn't work

db.placements.update({program_id:{$in:[113,107]},
                     keyword:{$regex:'^[0-9]', $options:'i'}}, 
                     {keyword:"+"+$keyword})

It cannot recognize $keyword, I also tried '.keyword', 'keyword', none of them works. Is there any way to reference the document itself like Java does, using 'this', so I can do something like

this.keyword: "+" + this.keyword
like image 450
user468587 Avatar asked Apr 03 '14 16:04

user468587


People also ask

Can we use regex in MongoDB?

MongoDB uses Perl compatible regular expressions (i.e. "PCRE" ) version 8.42 with UTF-8 support. For restrictions on particular syntax use, see $regex vs. /pattern/ Syntax. The following <options> are available for use with regular expression. Case insensitivity to match upper and lower cases.

How does regex work MongoDB?

MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support.


2 Answers

You'll have to use the $set operator in the update query to update a specific field. Also, you cannot concatenate string within an update query. One way to do this would be using cursor forEach() in the shell:

db.placements.find({program_id:{$in:[113,107]}, keyword:{$regex:'^[0-9]', $options:'i'}})
    .forEach(function(doc){ 
        db.placements.updateOne({_id:doc._id}, {$set:{"keyword":"+" + doc.keyword}})  
})
like image 181
Anand Jayabalan Avatar answered Oct 28 '22 15:10

Anand Jayabalan


No, you cannot reference a value on the document itself when querying like you can with SQL.

I would suggest querying the document, updating it on your web/app server and then updating the value back to mongodb.

You will also find that your update command above will wipe your entire document leaving only the keyword field. You should use the $set modifier to update a field or set of fields.

db.placements.update(
    {
        program_id:{$in:[113,107]}, 
        keyword:{$regex:'^[0-9]', $options:'i'}
    }, 
    { $set: {keyword: new_value}})
like image 24
Mark Unsworth Avatar answered Oct 28 '22 17:10

Mark Unsworth