Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update object in nested arrays in mongo db?

Tags:

json

mongodb

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");
}
like image 817
longda Avatar asked Aug 26 '10 20:08

longda


1 Answers

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.

like image 164
Niels van der Rest Avatar answered Oct 12 '22 23:10

Niels van der Rest