2

I have a JSON of form:

{
    "array":[
        {
            "node1":"value1",
            "node2":"value2"
        },
        {
            "node1":"value1",
            "node2":"value2"
        }
    ]
}

Now I have a Front End GUI from where I receive 2 parameters that need to be inserted in the array.

But if the first parameter value1 is already in the array then I just need to update the corresponding value2 in my database. If value1 is not present in array then insert a new object {"node1":"value1","node2":"value2"} in the array.

I need to do this using mLAB APIs. Reading the docs didn't help me to come up with the solution.

tester9
  • 93
  • 9

1 Answers1

0

As far as I know, there isn't a single query that can upsert documents in an array. You can either implement this in your application logic or use two queries. There are several two-query solutions. Here's one using $pull and $push:

curl https://api.mlab.com/api/1/databases/<db>/collections/<collection>?apiKey=apiKey \
-X PUT \
-H 'Content-Type: application/json' \
-d '{"$pull": {"array": {"node1": "value1"}}}'

curl https://api.mlab.com/api/1/databases/<db>/collections/<collection>?apiKey=apiKey \
-X PUT \
-H 'Content-Type: application/json' \
-d '{"$push": {"array": {"node1": "value1", "node2": "value2"}}}'

This acts to update the object where node1 is "value1", or add it to the array if it doesn't exist. This does depend on having unique values for the node1 properties.

Word of warning: mLab strongly recommends using one of the MongoDB drivers to connect to your database instead of the data API. Your API key will give full access to all data within the databases belonging to your mLab account. So if you distribute it in client-side applications to untrusted individuals, they can gain access to your account and your data. Feel free to email support@mlab.com if you need advice on alternatives.

tfogo
  • 1,416
  • 1
  • 14
  • 23