1

I need to sort inner object sort of a class with mongo db. i need to sort based on marks

Sample Json:

{"_id":"58e46f81c4734559ac8082f0","Name":"test","Students":[{"Name":"A","Marks":"988"}]}
{"_id":"58e46f81c4734559ac8082f1","Name":"sahir","Students":[{"Name":"sahir","Marks":"311"}]}

Here is the class:

public class  Student
    {


        [BsonId]
        public ObjectId Id { get; set; }
    
        [BsonElement]
        public string Name { get; set; }
        
        public ICollection <Students> Students { get; set; }

    }

    public class Students
    {
    
        public string Name { get; set; }
        
        public string Marks{ get; set; }

    }

Action

public IActionResult Index()
    {


        //Get the database connection
        mongoDatabase = GetMongoDatabase();
        var x = mongoDatabase.GetCollection<Student>("student").Find(FilterDefinition<Student>.Empty).ToList();


  
        var _dbContext = mongoDatabase.GetCollection<Student>("student");

// mongo db document collection student class students objects need to sort based on marks.
        _dbContext.Aggregate<Student>()
                         .Sort(x=> x.students.marks).Skip((page-1)*pageSize).Limit(100);
                          
                          .ToList();         -- how to do that sort in this line 


or 


    var result = _dbContext.Aggregate<Student>().Sort(new BsonDocument("Marks", 1)).ToList();



        return View(result);
    }

Note:

Don't provide linq Solution to convert asQuerable operators to do LINQ queries. This question is only based on an understanding of MongoDB aggregation sort and how to use that in C#.

No forum has any reference for internal objects sorting with c#.There are lots of examples of C# mongodb sorting without aggragtion

Problem: I have aggregation sort mongo shell query .. don't know to implement that in c#

1 Answer 1

2

are you trying to get a list of all students sorted by their marks? if so, try this:

var students = await collection.AsQueryable()
    .SelectMany(c => c.Students)
    .OrderBy(s => s.Marks)
    .Skip(50)
    .Take(10)
    .ToListAsync();

the easiest way to get the result you want is via the AsQueryable() interface.

if you must use the Aggregate() api, you can do the following:

var students = await collection.Aggregate()
    .Unwind(c => c.Students)
    .ReplaceWith<BsonDocument>("$Students")
    .Sort("{Marks:1}")
    .Skip(0)
    .Limit(10)
    .As<Student>()
    .ToListAsync();

test program:

using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MongoDB.Entities;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TestApplication
{
    public class Course : Entity
    {
        public IEnumerable<Student> Students { get; set; }
    }

    public class Student
    {
        public string Name { get; set; }
        public string Marks { get; set; }
    }

    public static class Program
    {
        private static async Task Main()
        {
            await DB.InitAsync("test");

            await new[] {
                new Course
                {
                    Students = new[] {
                        new Student { Name = "a", Marks = "100"},
                        new Student { Name = "b", Marks = "200"},
                    }
                },
                new Course
                {
                    Students = new[] {
                        new Student { Name = "d", Marks = "400"},
                        new Student { Name = "c", Marks = "300"},
                    }
                }
            }.SaveAsync();

        var students = await DB.Queryable<Course>()
            .SelectMany(c => c.Students)
            .OrderBy(s => s.Marks)
            .Skip(50)
            .Take(10)
            .ToListAsync();
        }
    }
}

Sign up to request clarification or add additional context in comments.

11 Comments

No i had already with linq to convert asquerable in memory collection and i don't want to use linq , need to use sort aggreation framework, because our framework designed based on that , and done filter, sort if dont have nested object working fine. but when inside nested have problem.
AsQueryable is done server-side, not in memory... but ok :-)
sorry i confused with ienumerable and asquereable. If it done serverside MongoDB don't have that operator I convert that collection to list and then i convert Linq asQuerable to do that operation , if i do that our base framework won't allow it. so i forced to use the aggregation framework..AsQueryable() filters in the SQL Server level and fetches the whatever record needed. So, it reduces the memory requirement and improves the performance of an application.
see my updated answer. the AsQueryable() endpoint doesn't do any filtering in memory. it just converts your LINQ instructions to mongo query language and sends that to the db server. so all you get back from the mongo server is the exact items you asked for.
that i know and i have already filtering with mongodb thats working fine only problem happen in Sort and have prepared this query I don't want to translate that query with LINQ translation. is there any other way to do with aggregation operators .dbContext.Aggregate<Student>().unwind(x=>x.students).Sort(new BsonDocument("Marks", 1)).Skip((page-1)*pageSize).Limit(100).ToList();
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.