$ push in the built-in array of documents

I would like to mark all posts read by "jim". Here is the stream structure:

db.threads.save({
    messages: [
        {
            read_by: ['bob', 'jim']
        },
        {
            read_by: ['bob']
        },
        {
            read_by: ['bob']
        }
    ]
})

As you can see, one message has already been read by "jim", the rest is just "bob". I would like to find and modify any inline documents to add "jim" to the array read_by.

This is where I got it:

db.threads.findAndModify({
    query: {
        'messages.read_by': {
            $ne: 'jim'
        }
    },
    update: {
        $push: {
            'messages.$.read_by': 'jim'
        }
    }
})

I get this error:

uncaught exception: findAndModifyFailed failed: "cannot join array using string field name [$]"

The request works with db.threads.find(), so I assume that the problem is related to the call update part findAndModify().

+2
source share
2 answers

, - , . . ,

db.threads.update({
    'messages.read_by': {
        $ne: 'jim'
    }
},
{
    $push: {
        'messages.read_by': {
            $each: ['jim']
        }
    }
}
)

. - http://docs.mongodb.org/manual/reference/operator/update/push/

, $each. read_by , . $each , .

+1

. . , .

: find() , jim , , messages .

+1

All Articles