MongoDB - 更新嵌套文档

时间:2016-05-13 20:53:34

标签: mongodb

我想在具有指定网址的相应文档中将嵌套的“已抓取”更新为True。

我对mongodb很新,我似乎无法弄明白,任何帮助都非常感激。

集合结构

{
    "_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
}

更新查询

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

2 个答案:

答案 0 :(得分:1)

在第一个文档搜索中使用链接并在第二个文档中设置更新值。您需要指定好的。$。crawled以指定要更新的数组元素。

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

答案 1 :(得分:0)

您应该使用$elemMatch来查询文档数组中的特定条目。匹配后,您可以使用$set更改值

此示例适用于find,但它也适用于更新。

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