Only fields are allowed in a $sort

edx
edx
Member
506 Points
24 Posts

I'm trying to do sort on the basis of child element which in list of object as:

_context.Orders.AsQueryable()
             .Where(predicate)
             .OrderBy(x => x.Items.OrderBy( x=> x.format.format ))
             .Skip(offset)
             .Take(limit)
             .ToList();
   [BsonIgnoreExtraElements]
    public class OrderDetail : Order
    {
        [BsonIgnoreIfNull]
        public List<Item> Items { get; set; }
    }
   [BsonIgnoreExtraElements]
    public class Item
    {
        public string id { get; set; }
        public Format format { get; set; }
    }

    [BsonIgnoreExtraElements]
    public class Format
    {
        public string format { get; set; }
    }

And getting following error:

Only fields are allowed in a $sort

 

Views: 1251
Total Answered: 2
Total Marked As Answer: 1
Posted On: 16-Dec-2021 04:11

Share:   fb twitter linkedin
Answers
Smith
Smith
None
2568 Points
74 Posts
         

Hi try with aggregation query as:

mongoDBService.GetCollection(COLLECTION_NAME).Aggregate()
             .Match(filterObject)
             .sort(Builders<Orders>.Sort.Ascending("Items.format.format"));
Posted On: 22-Dec-2021 05:48
Thanks. As linq implementation does not support child nod sorting. So instead of using .AsQueryable(), we can use .Aggregate() as in this post.
 - Priya  28-Dec-2021 03:31
Thanks Smith. Worked for me.
 - edx  28-Dec-2021 03:32
Priya
Priya
Participant
936 Points
28 Posts
         

Use .ToList() and then do sorting as:

_context.Orders.AsQueryable()
             .Where(predicate)
             .ToList()
             .OrderBy(x => x.Items.OrderBy( x=> x.format.format ))
             .Skip(offset)
             .Take(limit);

But Above will sort in memory of application server not on DB server. It can be suitable for fewer records only.

Posted On: 28-Dec-2021 03:23
 Log In to Chat