views:

22

answers:

1

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");
}
+1  A: 

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.

Niels van der Rest
Nice, I'll give it a try... thanks!
longda
That works! You're a god! :)
longda
@longda: Glad I could help :)
Niels van der Rest