Assuming I have the following document structure:
{
"name": "myProduct",
"perspectives" : [
{
"name": "p1",
"views" : [
{
"name": "v1"
},
{
"name": "v2"
}
]
},
{
"name": "p2",
"views" : [
{
"name": "v1"
},
{
"name": "v2"
}
]
}
]
}
How would I go about updating the document structure to add an "alias" field to each of the views?
Basically I'm looking to do something like perspectives.views.alias: "av1" for all perspectives.views.name: "v1".
The resulting structure would look like this:
{
"name": "myProduct",
"perspectives" : [
{
"name": "p1",
"views" : [
{
"name": "v1",
"alias": "av1"
},
{
"name": "v2",
"alias": "av2"
}
]
},
{
"name": "p2",
"views" : [
{
"name": "v1",
"alias": "av1"
},
{
"name": "v2",
"alias": "av2"
}
]
}
]
}
To clarify, I'd like to do something like this:
foreach (view in product.perspectives.views)
{
if (view.name == "p1")
view.add("alias", "av1");
}
-
Can't you pull the data with whatever language you're using, loop through it like you have at the bottom, and update it? Or are you trying to do it in a single query. If this is the case, check this out: mongodb.org/display/DOCS/Server-side+Code+ExecutionShane Reustle– Shane Reustle2010年08月26日 21:55:41 +00:00Commented Aug 26, 2010 at 21:55
-
Thanks Shane! Yeah, I'm doing it from the console as scripts rather than from an app and higher level language (like Java, for instance). I might go the app route though if it ends up being easier/more productive.longda– longda2010年08月27日 17:58:31 +00:00Commented Aug 27, 2010 at 17:58
1 Answer 1
You'll have to loop though your documents, the perspectives in each document and the views in each perspective. Then update the views and save the updated document. Something like this should do the trick:
db.products.find().forEach(function (product) {
product.perspectives.forEach(function (perspective) {
perspective.views.forEach(function (view) {
view.alias = "a" + view.name;
})
});
db.products.save(product);
})
You can paste this function into the Mongo shell and run it from there. As an alternative, you can save it in a file called updateProducts.js and run the file with the Mongo shell:
mongo nameOfDatabase updateProducts.js
The function will be executed on the server, so it should be quite fast.