Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb C# use skip-limit for nested array

Tags:

c#

mongodb

My class:

class Product
{
    public string _id {get; set;}
    public IEnumerable<Item> Items {get; set;}
    public int ItemsCount {get; set;}
}

class Item
{
    public string Name {get; set;}
}

I need to select Items only and process skip limit (paging) for them. Count I can store in the object. Is it possible to use mongo for that or should I put Items to another collection?

like image 946
Alex Gurskiy Avatar asked Apr 21 '26 22:04

Alex Gurskiy


1 Answers

we can have two scenarios here:

  1. We are always requesting ONE main document and need to have skip/limit on this particular array.

  2. We are requesting an unknown number of documents and then we could do skip/limit on a kind of merged array from all source ones.

Both solutions are using aggregation framework with $unwind stage, the diffrence is that $match in first case always returns only one document (let's say matched by objectId).

var aggregate = collection.Aggregate().Match(x => x.Id == ourNeededId)
     .Unwind("Items").Skip(3).Limit(3).Project<Product>(project);

As output we will get 3 documents which we can a) merge using $group server side or iterate and process in c# code.

EDIT

        var aggregate =
            collection.Aggregate()
                .Match(x => x._id == "some id here")
                .Unwind("Items")
                .Skip(3)
                .Limit(3)
                .Group(BsonDocument.Parse("{_id:{id:'$_id', ItemsCount:'$ItemsCount' },Items:{$push:'$Items'} }"))
                .Project<Product>(BsonDocument.Parse("{_id:'$_id.id', ItemsCount:'$_id.ItemsCount', Items:1  }"))
                .ToList();

Any comments welcome!

like image 192
profesor79 Avatar answered Apr 24 '26 10:04

profesor79