Sorting Problem

Top K Frequent Elements

Problem

Given an integer array and a number k, find the k most frequent elements in the array.

Example

{
"arr": [1, 2, 3, 2, 4, 3, 1],
"k": 2
}

Output:

[3, 1]

Solution

function mostFrequentWord(arr, k) {

  const freq = new Map();
  let result = [];
  let n = arr.length;

  for (let i = 0; i < n; i++) {

    let x = 0;
    if (freq.has(arr[i]) == true) {
      x = freq.get(arr[i]);
    }
    freq.set(words[i], x + 1);
  }

  let freqWordsSorted = new Map([...freq.entries()].sort((a, b) => b[1] - a[1]));

  for (let [key, value] of freqWordsSorted) {
    result.push(key);
    k--;
    if(!k) {
      break;
    }
  }

  console.log(result);
}

// given set of keys
let arr = [1, 2, 3, 2, 4, 3, 1];
let n = 2;

mostFrequentWord(arr, n);

MongoDB

Data Aggregation using C# and MongoDB

MongoDB can perform aggregation operations, such as grouping by a specified key and evaluating a total or a count for each distinct group.

Use the Group stage to group by a specified key. In the Group stage, specify the group by key in the _id field. Group accesses fields by the field path, which is the field name prefixed by a dollar sign $
  
Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.

  using System;   
  using System.Threading.Tasks;   
  using MongoDB.Bson;   
  using MongoDB.Driver;   
  namespace MongoDB   
  {   
   class Program   
   {   
    static void Main(string[] args)   
    {   
     DataGrouping(args).Wait();   
     Console.WriteLine("Press Enter");   
     Console.ReadLine();   
    }   
    static async Task DataGrouping(string[] args)   
    {   
     var _connectionString = "mongodb://localhost:27017";   
     var _client = new MongoClient(_connectionString);   
     var _database = _client.GetDatabase("blog");   
     var _collection = _database.GetCollection("users");   
     var _aggregate = _collection.Aggregate().Group(new BsonDocument { { "_id", "$ZipCode" }, { "count", new BsonDocument("$sum", 1) } });   
     var _results = await _aggregate.ToListAsync();   
    }   
   }   
  }   
MongoDB

Create Indexes using C# and MongoDB

The IMongoIndexManager.CreateOneAsync method is used to create an index on a collection. MongoDB automatically creates an index on the _id field upon the creation of a collection.

Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.

 using System;  
 using System.Threading.Tasks;  
 using MongoDB.Bson;  
 using MongoDB.Driver;  
   
 namespace MongoDB  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       CreateIndex(args).Wait();  
       Console.WriteLine("Press Enter");  
       Console.ReadLine();  
     }  
     static async Task CreateIndex(string[] args)  
     {  
       var _connectionString = "mongodb://localhost:27017";  
       var _client = new MongoClient(_connectionString);  
       var _database = _client.GetDatabase("blog");  
       var _collection = _database.GetCollection("users");  
   
       //Create a Single-Field Index  
       var _key = Builders.IndexKeys.Ascending("Email");  
       await _collection.Indexes.CreateOneAsync(_key);  
   
       //Creating a Compound Index  
       var _keys = Builders.IndexKeys.Ascending("Name").Ascending("Zipcode");  
       await _collection.Indexes.CreateOneAsync(_keys);  
     }  
   }  
 }  
   
MongoDB

Update data or documents of collection with C# and MongoDB

You can use the UpdateOneAsync method, UpdateManyAsync method, and ReplaceOneAsync method to update documents of a collection. The methods accept the following parameters:

  • a filter document to match the documents to update,
  • an update document to specify the modification to perform, and
  • an options parameter (optional).

You cannot update the _id field.

Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.

The following operation updates the first document with Name equal to “Himen”, to update the Email, Address1, City, ZipCode and Country field and the lastModified field. To specify a $set operation to update the Email, Address1, City, ZipCode and Country field, use the Set method of the UpdateDefinitionBuilder. To specify a $currentDate operation to update the lastModified field with the current date, use the CurrentDate method of the UpdateDefinitionBuilder.

The $set operator replaces the value of a field with the specified value.

The $currentDate operator sets the value of a field to the current date, either as a Dateor a timestamp. The default type is Date.

 using System;  
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongoDB
{
class Program
{
static void Main(string[] args)
{
UpdateDoc(args).Wait();
Console.WriteLine("Press Enter");
Console.ReadLine();
}
static async Task UpdateDoc(string[] args)
{
var _connectionString = "mongodb://localhost:27017";
var _client = new MongoClient(_connectionString);
var _database = _client.GetDatabase("blog");
var _collection = _database.GetCollection("users");
var _filter = Builders.Filter.Eq("Name", "Test");
var _update = Builders.Update
.Set("Email", "email2test@zzzz.com")
.Set("Address1", "other street")
.Set("City", "XYZ")
.Set("ZipCode", "390011")
.Set("Country", "other country")
.CurrentDate("lastModified");
var _result = await _collection.UpdateOneAsync(_filter, _update);
}
}
}