0

I find a lot of examples with js queries for Mongodb. For example the following code were it is find duplicates in the collection :

db.collection.aggregate(
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
)

I understand that equivalents is something like the following:

var query = collection.Aggregate().Match(some lambda function).Group(some lambda funtion) });

But I do not see who to translate-map each statement to lambda function.

Can someone explain how to translate-map can be done with an example?

Thank you for your time.

EDIT:

I pass some example code to be more spesific: My Main

static void Main(string[] args)
    {
        MongoCRUD db = new MongoCRUD("MyDB");
        db.FindDouplicateValues<GlobalUrbanPoint>("MyColection");
    }

My model class:

public class GlobalUrbanPoint 
    {
        [BsonId]
        public ObjectId  Id{ get; set; }
        public string NAME { get; set; }
        public int LATLONGID { get; set; }
        public double LATITUDE { get; set; } 
        public double LONGITUDE { get; set; }
    }

And for the operation i use MongoCRUD

public class MongoCRUD
    {
        private IMongoDatabase db;
        // Connect to DataBase 
        public MongoCRUD(string database)
        {
            var client = new MongoClient();
            db = client.GetDatabase(database);
        }
        public void FindDouplicateValues<T>(string table) where T : GlobalUrbanPoint
        {
            var collection = db.GetCollection<T>(table);
            //Find the duplicates by LATLONGID. My syntax is wrong
            var query = collection.Aggregate().Group(t => t.LATLONGID ).Match(g=>g.Count()>1);
        }

     }
  • Hard to say without some actual data, but in general: `var duplicates = collection.GroupBy(t => t.WhatEveryValueCanBeDuplicate).Where(g => g.Count() > 1);` - note that the 'group by' value can include multiple values, you just have to use an anonymous object. – stuartd Jun 14 '20 at 23:52
  • @stuartd I have edit my question. It is helping to give me an example with actual data ??. Thanks for your response. – Giannis Aggelis Jun 15 '20 at 07:15

1 Answers1

1

The C# fluent aggregation in the C# driver maps very well to the normal stages that you use in javascript. Check out the below for an example.

var client = new MongoClient();
var db = client.GetDatabase("db");
var collection = db.GetCollection<Person>("people");

// Clean out database to start off with.
await db.DropCollectionAsync(collection.CollectionNamespace.CollectionName);

// Insert in to data to play around with
// 1x James, 2x Mary, 3x Jennifer, 1x John
await collection.InsertManyAsync(new[]
{
    new Person{ Name = "James"},
    new Person{ Name = "Mary"},
    new Person{ Name = "Jennifer"},
    new Person{ Name = "John"},
    new Person{ Name = "Jennifer"},
    new Person{ Name = "Mary"},
    new Person{ Name = "Jennifer"},
});


// Run our aggregation
var list = await collection.Aggregate()
    .Group(person => person.Name, persons => new { Id = persons.Key, Count = persons.Count() })
    .Match(x => x.Count > 1)
    .Project(x => new { Name = x.Id })
    .ToListAsync();

// Name: Mary
// Name: Jennifer
foreach (var item in list)
{
    Console.WriteLine($"Name: {item.Name}");
}

Alternatively, if you can't find something that fits you can just use the json as a string in C#

var list = await collection.Aggregate()
    .Group(@"{ ""_id"": ""$name"", ""count"": { ""$sum"": 1 } }")
    .Match(@"{""_id"" :{ ""$ne"" : null } , ""count"" : {""$gt"": 1} }")
    .Project(@"{""name"" : ""$_id"", ""_id"" : 0}")
    .ToListAsync();

There are a few downsides to using the JSON syntax in C#, these are you can get security issues with injection attacks, and also you don't get any type safety from C# compiler.

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77