Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

How to do aggregation sort in mongodb inner object with c#

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#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...