A
A
artem782016-09-21 21:27:27
NoSQL
artem78, 2016-09-21 21:27:27

How to remove a field from an array of nested documents in MongoDB?

There is a collection of documents of the following content:

{
    "url" : "http://site.ru/url1",
    "checks" : [
        {
            "check_date" : ISODate("2016-09-20T21:21:06.845Z"),
            "result" : 1,
            "html" : "<html><body>..."
        },
        {
            "check_date" : ISODate("2016-09-20T21:22:07.141Z"),
            "result" : 2,
            "html" : "<html><body>..."
        },
        {
            "check_date" : ISODate("2016-09-20T21:23:05.526Z"),
            "result" : 3
        }
    ]
}

Tell me how to write a request to remove the "html" field for all elements of the "checks" array in all documents (moreover, some of the html field is already missing)?
I tried to do it in the following ways, but apparently this is not correct:
> db.items.update({}, {$unset: {'checks.html':1}}, false, true);
WriteResult({ "nMatched" : 18, "nUpserted" : 0, "nModified" : 0 })
 
> db.items.update({}, {$unset: {'checks.$.html':1}}, false, true);
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 16837,
        "errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: checks.$.html"
    }
})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
artem78, 2016-09-22
@artem78

Made it this way:

db.items.find().forEach(function(doc) {
  if (doc.checks) {
            for (var i in doc.checks) {
                    if (doc.checks[i].html) {
                            delete doc.checks[i].html;
                    }
            }
            db.items.update({_id: doc._id}, {$set: {"checks": doc.checks}});
  }
});

N
napa3um, 2016-09-21
@napa3um

stackoverflow.com/questions/10522347/mongodb-updat...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question