9

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

2 Answers 2

17

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}})  
})
Sign up to request clarification or add additional context in comments.

Comments

4

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}})

1 Comment

Referencing a var in the doc itself is now possible (v4.2, 2019) with the pipeline form of $update.

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.