Updating a single field in MongoDB in a single embedded document

We have built-in 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 above document is contained in an array, I am having trouble choosing it from a 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 one warning with identifier "4fa7fd60e5be08bcc9000644".

+3
source share
1 answer

You can use the positioning operator to identify an array element:

$ Positional operator

The $ operator (by itself) means "the position of the element of the matched array in the request." Use this to find an element of an array and then process it.

So maybe something like:

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

, , .


, , , :

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

- , . :matches , $ -, .

+5

All Articles