iamsaksham
iamsaksham

Reputation: 2949

Nodejs-mongodb: Update document structure for all documents in a collection

I have a collection data which has around 300k entries and its document looks like

{
    "_id" : ObjectId("5xxx85"),
    "user_id" : "1",
    "name" : "test",
    "user_private" : "0"
}

now i want to update all the documents in this collection and new document will look like

{
    "_id" : ObjectId("5xxx85"),
    "rid" : "1",
    "user_name" : "test",
    "is_private" : "private",
    "is_moderator" : "true",
    "amount" : "11111"
}

i.e i need to add new fields, update field names and check if user_private = 0 then put is_private as private or else put is_private as not_private.

I am a bit new so I am not able to get how can i do this efficiently as entries are around 300k. Please suggest some ways, pseudo code will be really helpful

Upvotes: 1

Views: 1078

Answers (1)

Akinjide
Akinjide

Reputation: 2763

To update a document a filter criteria. Check pseudo code below and follow link to read more.

You'll need to have an existing value for user_private

db.messages.updateMany([
  { "user_private" : 0 }, // filter.
  { $set: { 
      "user_private" : "private",
      "is_moderator" : "true"
    } 
  }, // update.
  {
   upsert: true
  }
]);

upserts - Creates a new document if no documents match the filter or Updates documents that match the filter based on the filter and update parameters provided.

Upvotes: 2

Related Questions