Adders
Adders

Reputation: 665

MongoDB - Updating a nested document

I'm wanting to update the nested 'crawled' to True within the appropriate document with the specified URL.

I'm fairly new to mongodb and I just can't seem to figure this out, any help is much appreciated.

collection structure

{
    "_id": {
        "$oid": "56e9978732beb44a2f2ac6ae"
    },
    "domain": "techweekeurope.co.uk",
    "good": [
        {
            "crawled": false,
            "added": {
                "$date": "2016-03-16T17:27:17.461Z"
            },
            "link": "/workspace/microsoft-dell-windows-surface-106648"
        },
        {
            "crawled": false,
            "added": {
                "$date": "2016-03-16T17:27:17.461Z"
            },
            "link": "/workspace/new-street-view-images-raise-privacy-concerns-5850"
        },
        {
            "crawled": false,
            "added": {
                "$date": "2016-03-16T17:27:17.461Z"
            },
            "link": "/workspace/quiz-of-the-week-dell-reborn-106744"
        }
    ],
    "bad": [],
    "link_found": false,
    "subdomain": "http://www.",
    "crawled": true
}

update query

self.collection.update({'good.link':'/workspace/microsoft-dell-windows-surface-106648'}, {'crawled': True})

Upvotes: 0

Views: 43

Answers (2)

Mingo
Mingo

Reputation: 78

You should use $elemMatch to query for specific entries in an array of a document. Once you have matched it, you can use $set to change the value

This example is for find but it works with update as well.

db.survey.find(
   { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)

Upvotes: 0

Lahar Shah
Lahar Shah

Reputation: 7644

In first document search with link and in second document set updated value. You need to specify good.$.crawled to specify that element of array to update.

.update(
        {'good.link':'/workspace/microsoft-dell-windows-surface-106648'}, 
        {
          $set : {'good.$.crawled': true} 
        }
)

Upvotes: 1

Related Questions