Update single field in MongoDB in a single embedded document

mongodb, ruby

Solution

You can probably use the positional operator to identify the array element:

The $ positional operator

The $ operator (by itself) means "position of the matched array item in the query". Use this to find an array member and then manipulate it.

So perhaps something like:

User.collection.update(
    { :_id => user.id, :matches => BSON::ObjectId('4e40238dbc9f6ec5a6000eed') },
    { :$set => { 'alert.matches.$' => matches } }
)

But as Sergio notes, it is difficult to tease out the structure of your documents based on the limited information in your question.

Looks like more information came in after I answered and it looks like:

{ :$set => { 'alerts.$.matches' => ... } }

is what you need. And you will need to include `:matches` in the query so that `$` has something to refer to.

Problem

We have some embedded documents that look like this: ``` { "_id" : ObjectId("4e402353bc9f6ec5a6000001"), "first_name" : "Chris", "last_name" : "Jones", "alerts" : [ { "_id" : ObjectId("4f7cd6ffc067db00070022d4"), "name" : "Default", "email_frequency" : "weekly", "interested_industries" : [ "Computer Software", "Internet" ], "interested_employers" : [ "Facebook", "AOL" ], "interested_skills" : [ ], "matches" : [ ObjectId("4ee46a2a0dd0c70017000365"), ObjectId("4efa1707bacfa40001012b65"), ObjectId("4e402376bc9f6ec5a6000a7a"), ObjectId("4e4e0eb8d052fc4028021f66"), ObjectId("4ee55d8500ca410014000003"), ObjectId("4ee63d06d96b850001008688"), ObjectId("4e57be7ed052fc606a002335"), ObjectId("4f05d47d9ce340001702ba42"), ObjectId("4f200ffcaf5f34000e0021a4"), ObjectId("4e4de701d052fc33da00052f") ], "updated_at" : ISODate("2012-05-03T18:26:14.774Z") } ] } ``` Since the document above is contained in an array, I'm having trouble picking it out form the selector with something like this: ``` User.collection.update({"_id" => user.id}, {:$set => {"alert.matches" => matches}}) ``` But this will update all #alerts matches. I just want to update the one alert with the ID "4fa7fd60e5be08bcc9000644".

Original source