Reputation: 8162
An example of a document from a collection named categories in my MongoDB Database is:
{
"_id": "Cookbooks",
"parent": "Non-Fiction",
"ancestors": [
"Books",
"Non-Fiction",
"Cookbooks"
]
}
All other entries in this category collection have this same schema and there are hundreds of them. What I want to do is insert an additional "All" element at the first position of the ancestors array to all those 100 entries/documents. for eg:
{
"_id": "Cookbooks",
"parent": "Non-Fiction",
"ancestors": [
"All",
"Books",
"Non-Fiction",
"Cookbooks"
]
}
Is there a way that doesn't require writing a complete script and can be done just using the mongo shell or any other simple way? :/
Upvotes: 0
Views: 191
Reputation: 16805
To push "All" in ancestors array at the first position you should use $postiion: 0
and to update all records should use multi:true
in mongoDB:
db.collectionName.update({},
{ $push: { "ancestors": {$each: ["All"], $position: 0} }},
{multi:true})
in mongoose :
ModelName.update({},
{ $push: { "ancestors": {$each: ["All"], $position: 0} }},
{multi:true},
function(err, result) {
if(err) {
// return error
}
//return success
});
Upvotes: 1
Reputation: 1515
You can push the value via mongo shell.
Here is the query:
db.w6.update(
{ _id: "Cookbooks"},
{ $push: { "ancestors": "All" }}
);
Upvotes: 0