MongoDB Tip & Tricks

Commands

Update a specific field value for a collection:

Example: Update “CampaignId” field across entire collection

db.Prospects.update(
{}, {$set: {CampaignId: ObjectId('54ec891dc8efe23e3e0fb1ef')}}, { multi: true }
)

Remove a specific field value for a collection:

Example: Remove “CampaignId” field across entire collection

db.Prospects.update(
   { CampaignId: "54ec891dc8efe23e3e0fb1ef" },
   { $unset: { ZipCode: ""} }
)

Filter out documents from a collection based on list of Id’s, equivalent to SQL “IN”
Example: Retrieve documents with list of “ProductId”s across entire collection.

List ids=new List();
for(int index=0;index<Products.Count;index++)
{
  ids.Add(ObjectId.Parse(Products[index].Id));
}
var filter = Builders.Filter.Eq("ProductId", ids);
return await _database.GetCollection("AnalyticsSummary")
.Find(filter)
.ToListAsync().ConfigureAwait(false);

Rename a specific field value for a collection:
Example: Rename “CampaignId” field to “CampaignName” across entire collection

db.getCollection('CampaignSummary').update({},{ $rename: { "CampaignId": "CampaignName" } }, false, true )

The false, true in the method above are: { upsert:false, multi:true }. You need the multi:true to update all your records.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s