Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uncaught exception: can't have . in field names

I'm trying to update a group of documents in my members_copy collection.

db.members_copy.find({"fields.shop.id": 321}).forEach(function(myDoc) {     
    db.members_copy.update({ "_id": myDoc._id}, { "fields.shop": [{"id": 319, "value": "Los Angeles"}] });
});

I get the following error:

uncaught exception: can't have . in field names [fields.shop]

I understand the problem, but I can't find a solution to this, so I'd appreciate any help I can get.

like image 463
Repox Avatar asked Mar 05 '14 08:03

Repox


1 Answers

If you don't have anything in your fields sub-document you can do this with $set, which you should be using anyway if you have anything other than just fields as a field in your document.

db.members_copy.update(
    { "_id": myDoc._id},
    { "$set": { "fields.shop": [{"id": 319, "value": "Los Angeles"}] } }
);

But what you can't do is add items to a sub-document without replacing the whole thing. So if you wanted to add shop where there was an existing bar you would need do this

db.members_copy.update(
    { "_id": myDoc._id},
    { "$set": { 
        "fields": {
            "bar": "foo",
            "shop": [{"id": 319, "value": "Los Angeles"}]
         }
    }
);

Just a peril of using a sub-document in this way.

like image 90
Neil Lunn Avatar answered Oct 09 '22 17:10

Neil Lunn