timber535
timber535

Reputation: 435

Add key-value pair to collection in mLab

I have a collection in mLab and need to add a JSON key-value pair.
What are some ways to do this for all documents in the collection,
without editing each document manually.

    {
        "_id": {
            "$oid": "5b76acb78e7ea90016b46e6p"
        },
        "title": "document foo",
        "new key": "new value",

    }

Upvotes: 0

Views: 38

Answers (2)

timber535
timber535

Reputation: 435

Solved it using Mongo shell:

try {db.collection.updateMany({}, 
  { $set: {"new key" : "new value"} }); 
 } catch (e) { 
    print(e); 
}

Upvotes: 0

Eldar
Eldar

Reputation: 10790

You need to use the option m=true which updates all the documents matching criteria. And if you don't pass the criteria basically it updates every document in the collection.

$.ajax( { url: 'https://api.mlab.com/api/1/databases/your-db/collections/your-collection?apiKey=yourAPIKey&m=true',
          data: JSON.stringify( { "$set" : { "new key" : "new value" } } ),
          type: "PUT",
          contentType: "application/json" } );

Documentation

Upvotes: 1

Related Questions